简体   繁体   中英

Creating an object from html elements using JavaScript and jQuery

I want to create an object from html elements using JavaScript and jQuery.

The object i want to create is

{
  array:[{infraStructureType: 'value', hostId: 'value'}, {infraStructureType: 'value', hostId: 'value'}]
}

So my code to create above object is

  var obj = {}, dataObj = {compareESX: []};
  $('.checkBox:checked').each(function () {
    obj.infraStructureType = $(event.target).attr('hostId');
    obj.hostId = $(event.target).attr('infrastructureType');
    console.log(obj);
    dataObj.compareESX.push(obj);
    console.log(dataObj);
  });

In above code "console.log(obj)" gives correct output but, when i push it in array "dataObj.compareESX" Only information of last 'obj' is getting pushed number of times the each loop executes.

JS uses Call by reference method.So when update obj it changes all values. You need to do deep copy.Use this

dataObj.compareESX.push(JSON.parse(JSON.stringify(obj)));

Try this: FIDDLE We need to define the obj again to clear the previous values.

var dataObj = {compareESX: []};
  $('.checkBox:checked').each(function (e) {
    var obj = {};
    obj.infraStructureType = $(this).attr('hostId');
    obj.hostId = $(this).attr('infrastructureType');
    //console.log(obj);
    dataObj.compareESX.push(obj);
    //console.log(dataObj);
  });
console.log(dataObj);

You have to put your object definitions var obj = {} inside your each loop. Right now you are using the same object for every entry in the loop. Instead, you should create a new object for every checkbox over which you loop.

var dataObj = {compareESX: []};
$('.checkBox:checked').each(function () {
  var obj = {};
  obj.infraStructureType = $(event.target).attr('hostId');
  obj.hostId = $(event.target).attr('infrastructureType');
  console.log(obj);
  dataObj.compareESX.push(obj);
  console.log(dataObj);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM