使用内部对象将HTML表单字段转换为JSON对象 [英] Convert an HTML form field to a JSON object with inner objects

查看:120
本文介绍了使用内部对象将HTML表单字段转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下HTML形式:

Given the following HTML form:

<form id="myform">
  Company: <input type="text" name="Company" value="ACME, INC."/>
  First Name: <input type="text" name="Contact.FirstName" value="Daffy"/>
  Last Name: <input type="text" name="Contact.LastName" value="Duck"/>
</form>

将这种形式的javascript中的表格序列化为JSON对象的最佳方式是什么:

What is the best way serialize this form in javascript to a JSON object in the format:

{
  Company:"ACME, INC.",
  Contact:{FirstName:"Daffy", LastName:"Duck"}
}

还请注意,可能有多个"1".登录字段名称.

Also note that there might be more than 1 "." sign in the field name.

推荐答案

我认为您要做的是:对于每个输入,首先在分隔符(."字符)处拆分名称.现在,您有了一个名称数组.然后,您可以遍历该数组,确保每次遇到新名称段时,目标程序集"对象(和子对象)都具有容器.当数组中包含1个元素时,只需添加值即可.

I think that what you'd do is this: for each input, first split the name at the separators (the '.' characters). Now, you have an array of names. You can then iterate through that array, making sure that your target "assembly" object (and sub-objects) have containers every time you come across a new name segment. When the array has 1 element in it, you simply add the value.

$.fn.extractObject = function() {
  var accum = {};
  function add(accum, namev, value) {
    if (namev.length == 1)
      accum[namev[0]] = value;
    else {
      if (accum[namev[0]] == null)
        accum[namev[0]] = {};
      add(accum[namev[0]], namev.slice(1), value);
    }
  }; 
  this.find('input, textarea, select').each(function() {
    add(accum, $(this).attr('name').split('.'), $(this).val());
  });
  return accum;
});
// ...

var object = $('#myform').extractObject();

我只是整理了一下,所以可能会有一个或两个错误.我不记得是否所有的浏览器都具有切片"功能,但我认为它们确实有.

I just sort-of made that up so there might be a bug or two; I can't remember whether all the browsers have "slice" but I think they do.

(我忘记了对split()的所有重要呼叫)

(edit: I forgot the all-important call to split())

这篇关于使用内部对象将HTML表单字段转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆