使用jQuery和JavaScript从HTML创建对象数组

时间:2018-11-23 11:56:52

标签: javascript jquery html

我有多个带类行的div,每个div包含带类头和正文的div。

现在,我想从标题和正文中读取输入的值,并将它们存储在如下所示的对象数组中。

HTML:

<form id="myForm">
    <div class="row">
        <div class="header">
            <input type="checkbox" value="1">
        </div>
        <div class="body">
            <input type="checkbox" value="11">
            <input type="checkbox" value="12">
        </div>
    </div>
    <div class="row">
        <div class="header">
            <input type="checkbox" value="2">
        </div>
        <div class="body">
            <input type="checkbox" value="21">
            <input type="checkbox" value="22">
        </div>
    </div>
    <div class="row">
        <div class="header">
            <input type="checkbox" value="3">
        </div>
        <div class="body">
            <input type="checkbox" value="31">
            <input type="checkbox" value="32">
        </div>
    </div>
</form>

所需的输出 我想生成(使用jQuery)类似于以下内容的对象数组:

[
    {
        "line1": 1,
        "line2": [11, 12]
    },
    {
        "line1": 2,
        "line2": [21, 22]
    },
    {
        "line1": 3,
        "line2": [31, 32]
    }
]

1 个答案:

答案 0 :(得分:-1)

这应该可以解决问题!

let data = [];

//loop over each element with row class
$.each($(".row"), function(i, row) {

  //get the value of the header input within that row
  let headerVal = parseFloat($(row).find(".header input").val());


  let bodyVals = [];

  //loop over each body input within the row
  $.each($(row).find(".body input"), function(i, body) {

    //push the value of each body input into tho bodyVals array
    bodyVals.push(parseFloat($(body).val()));
  });

  //create an object containing the header and body values
  //and push it to the data array
  data.push({
    line1: headerVal,
    line2: bodyVals
  });
});

console.log(data);

JSFiddle:https://jsfiddle.net/so6bzwn7/26/