0

I want to add a property to an array of objects from another existing array (both from the same length)

Example:

var array1 = [1, 2, 3];
var array2 = [{word: "hey"}, {word: "hello"}, {word: "world"}]

//Wanted Outcome: array2 = [{word: "hey", id: 1}, {word: "hello", id: 2}, {word: "world", id: 3}]

What I've tried:

for(var i=0; i<array1.length; i++){
    for(var j= 0; j<array2.length; j++){
       array2[j].id = array1[i];
  }
}
//Outcome Im getting: array2 = [{word: "hey", id: 3}, {word: "hello", id: 3}, {word: "world", id: 3}]

How can I add a different property based on the first array length to the second array?

2 Answers 2

2

This is what you need

array2.forEach((item, i) => {
  item.id = array1[i]
})
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.