将属性从其他数组添加到对象数组-JS

时间:2020-10-28 16:30:59

标签: javascript loops

我想向另一个现有数组(长度相同)的对象数组添加属性

示例:

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}]

我尝试过的事情:

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}]

如何根据第一个数组的长度向第二个数组添加其他属性?

2 个答案:

答案 0 :(得分:2)

这就是您需要的

array2.forEach((item, i) => {
  item.id = array1[i]
})

答案 1 :(得分:1)

您在这里不需要嵌套循环。只需一级循环,即可使用i作为两个索引

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

更干净的方法是使用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);

相关问题