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

使用jQuery和javascript从HTML创建对象数组,javascript,jquery,html,Javascript,Jquery,Html,我有许多带有类行的div,每个div包含带有类头和类体的div 现在,我想从header和body读取输入值,并将它们存储在如下所示的对象数组中 HTML: 这应该能奏效 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

我有许多带有类行的div,每个div包含带有类头和类体的div

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

HTML:


这应该能奏效

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:

到目前为止你都尝试了什么?@AlivetoDie:我对javascript还不熟悉。所以创建这个JSON有点困惑。所以,看看关于jQuery选择器的书,选择像$input[type='checkbox']这样的元素。然后,您将有一个jQuery HTML对象的集合,您可以使用每个对象来迭代,然后获取其值。您还可以检查输入的父项。只要在jQuery文档上研究一下,为什么会被否决?Andreas补充道:“它的功能完全符合要求,并且在JSFIDLE中也能正常工作。这不是我的反对票,但向初学者抛出一堆过于复杂的代码而不作任何解释是没有帮助的。”
[
    {
        "line1": 1,
        "line2": [11, 12]
    },
    {
        "line1": 2,
        "line2": [21, 22]
    },
    {
        "line1": 3,
        "line2": [31, 32]
    }
]
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);