简体   繁体   中英

Add JavaScript object to an existing JavaScript object in for loop

I am trying to append a JavaScript object to an existing JavaScript object in the loop.

var object1 = { key1: true, header: 'Title A', Size: 100 };
$.each(elements, function (i, item) {
  let headerDisplay = '';
  headerDisplay = this.title;
  var row = { key1: true, header: '' + headerDisplay + '', Size: 100 };
  Object.assign(object1, row);
});

I have tried with Object.assign() , but it is giving only the last object. Expecting output array similar to

var finalObject = [
  { key1: true, header: 'Title A', Size: 100 },
  { key1: true, header: 'Title1', Size: 100 },
  { key1: true, header: 'Title2', Size: 100 },
  ...
];

Please let me know how can we add objects to an existing one in loop

since you are already using jQuery why not try the $.extend() functionality? it should look something like this:

 var object1 = { "key1": true, "header": "Title A", "Size": 100}; $.each(elements, function (i, item) { let headerDisplay = ''; headerDisplay = this.title; var row = { "key1": true, "header": ""+headerDisplay+"", "Size": 100}; $.extend(object1, row) });

keep in mind that this method will modify the first object1. If that is not the intended behavior you could pass an empty object as the first argument of the function and pass the result to another variable like this:

 const newObject = $.extend({}, object1, row)

Not sure what you are trying to do but perhaps there are better alternatives to that. Trying to keep a collection of your objects in an array may be another feasible solution. Good luck!!

please try it...:

 var object1 = { "key1": true, "header": "Title A", "Size": 100}; var res = [object1]; $.each(elements, function (i, item) { let headerDisplay = ''; headerDisplay = this.title; var row = { "key1": true, "header": ""+headerDisplay+"", "Size": 100}; res.push(row); });

now you have res as finalObj .

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