简体   繁体   中英

JavaScript iterate through assign values of array to object

I have object with dynamic quantity of properties and array with dynamic quantity of items in it. I need to iterate through both of them and assign values of array to property of object.

var obj = {
  property1: null,
  property2: null,
  .....
};

var array = ["some value1", "some value2"...];

Must be

var obj = {
  property1: "some value1",
  property2: "some value2",
  .....
}

If you literally have property1 , etc., then it's quite straightforward, because we can use the array index and brackets notation to build the property name from that index (plus one):

 var obj = { property1: null, property2: null //..... }; var array = ["some value1", "some value2"/*...*/]; array.forEach(function(value, index) { // vvvvvvvvvvvvvvvvvvvvvvvv------ string concat to build the property name obj["property" + (index + 1)] = value; // ^------------------------^----- brackets notation to refer to the property // using a runtime-defined name }); console.log(obj); 

Here is my answer. If name of property in dynamic then,

 var obj = { property1: null, property2: null, }; var array = ["some value1", "some value2"]; var i=0 for (var index in obj) { if (obj.hasOwnProperty(index)) { obj[index]=array[i]; } i++; } console.log(obj); 

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