Add Property to Object Array From Other Array – JS

You don’t need a nested loop here. Just you one level for loop and use i as both the indices

var array1 = [1, 2, 3];
var array2 = [{word: "hey"}, {word: "hello"}, {word: "world"}]
for(let i = 0; i < array2.length; i++){
  array2[i].id = array1[i];
}
console.log(array2);

Cleaner way for doing this is to use map()

var array1 = [1, 2, 3];
var array2 = [{word: "hey"}, {word: "hello"}, {word: "world"}]
array2 = array2.map((x, i) => ({...x, id: array1[i]}));
console.log(array2);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top