将html输入数组转换为JS对象

时间:2017-01-25 08:34:18

标签: javascript html

我有将HTML输入数组转换为Javascript对象的问题。

我有以下表格:

<form>
    <input name="element[el11][el21]" value="a">
    <input name="element[el11][el22]" value="b">
    <input name="element[el12][el21]" value="c">
    <input name="element[el12][el22]" value="d">
</form>

我希望有对象:

 {
        el11: 
        {
            el21: a
            el22: b
        },
        el22:
        {
            el21: c
            el22: d
        }
 }

有没有办法简单地做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以使用Array#reduce方法两次来获得结果。

var res =
  // get all iput elements in the form and convert into array
  // for iterating easily, use [].slice.call() for older browser
  Array.from(document.querySelectorAll('form input'))
  // iterate over the element, you can use forEach with an object defined
  .reduce(function(obj, ele) {
    // cache input value and name
    var val = ele.value,
      name = ele.name;

    // get the content within the square bracket and split 
    name.slice(name.indexOf('[') + 1, name.lastIndexOf(']'))
      .split('][')
      // iterate over the splitted array to generate the nested property  
      .reduce(function(o, k, i, arr) {
        // check current value is last elemnt, then assin the input value as property value
        if (arr.length - 1 == i)
          return o[k] = val;
        // else create a nested object if not defined and return the nested object
        return o[k] = o[k] || {};
        // set initial value as the object
      }, obj)
      // return the object reference
    return obj;
    // set the initial value as an empty object
  }, {});

console.log(res);
<form>
  <input name="element[el11][el21]" value="a">
  <input name="element[el11][el22]" value="b">
  <input name="element[el12][el21]" value="c">
  <input name="element[el12][el22]" value="d">
</form>

答案 1 :(得分:2)

您可以根据[...]

中的值循环元素并创建对象

&#13;
&#13;
var inputs = document.querySelectorAll('input[name^="element"]');
var output = {};
// regex to match `[...]`
const regex = /(?!^|\[)\w+(?=\]|$)/g

// Loop over inputs
for(var i = 0; i< inputs.length; i++){
  // Get name and matching attrs.
  var attr = inputs[i].getAttribute('name').match(regex);
  // Create a temp variable to store value of last refered object.
  var t = output;
  for(var j = 0; j< attr.length; j++){
    // Initialize values
    if(t[attr[j]] === undefined){
      t[attr[j]] = {}
    }
    // If last value, assign value to leaf node
    if(j === attr.length - 1) 
      t[attr[j]] = inputs[i].value;
    // Set temp to point to current node
    else
      t = t[attr[j]]
  }
}

console.log(output)
&#13;
<form>
  <input name="element[el11][el21]" value="a">
  <input name="element[el11][el22]" value="b">
  <input name="element[el12][el21]" value="c">
  <input name="element[el12][el22]" value="d">
</form>
&#13;
&#13;
&#13;