简体   繁体   English

从同一索引处的数组向索引处的对象添加属性

[英]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. 我的目标是从wordArray添加的每个字作为一个新的属性基于指数peopleArray每个对象。

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". 例如,单词“ Banana”在wordArray的索引为0处,因此它将被添加到对象在peopleArray的同一索引(即“ 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]

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM