简体   繁体   中英

Add attribute to an object at index from array at same index

I have two arrays, one with objects containing multiple attributes:

var peopleArray = [{name: 'James', lastname: 'Stanley'}, {name: 'Roger', lastname 'Moore'}];

And one array with random words:

var wordArray = ['Banana', 'Sword'];

My goal is to add each word from wordArray as a new attribute to each object in peopleArray based on index.

Eg the word "Banana" is at index 0 in wordArray so it will be added to the object at the same index in peopleArray, which is "James".

I hope it was clear, any guidance in any way appreciated! I really don't know how to achieve this

This is really pretty simple:

const n = Math.min(peopleArray.length, wordArray.length);
for (let i = 0; i < n; i++) {
    peopleArray[i].word = wordArray[i];
}
for (var index = 0; index < peopleArray.length; index++) {
    peopleArray[index][nameOfNewAttr] =wordArray[index]

}

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