javascript - JavaScript:如何将数组中的值添加到来自不同数组的对象属性?
问题描述
我哪里错了?我正在做某事。我正面临这个问题。
let array1 = [{
id: 1,
profile: ''
}, {
id: 2,
profile: ''
}, {
id: 3,
profile: ''
}]
let array2 = ['name1', 'name2', 'name3']
array1.forEach(function(value) {
for (let i = 0; i < array2.length; i++) {
return value['profile'] = array2[i]
}
})
console.log(array1);
所需输出:
array1 = [{id:1, profile: 'name1'}, {id:2, profile: 'name2'}, {id:3, profile: 'name3'}]
我尝试了以下代码:
array1.forEach(function(value) {
for(let i=0; i<array2.length; i++){
return value['profile'] = array2[i]
}
})
但我得到以下输出:
[ { id: 1, profile: 'name1' },
{ id: 2, profile: 'name1' },
{ id: 3, profile: 'name1' } ]
请指导我!
解决方案
您共享的代码混淆了一些可能导致您的问题的概念。
- Array.forEach 不带返回值
- 改变现有变量通常会导致错误
- 您还循环整个第二个数组,并始终将数组值 1 设置为结果。
相反,让我们.map
用来解决这些问题。
const array1 = [{id:1, profile: ''}, {id:2, profile: ''}, {id:3, profile: ''}]
const array2 = ['name1', 'name2', 'name3']
const array3 = array1.map(function (array1Item, index) {
return {
...array1Item,
profile: array2[index],
};
});
在这里,我们永远不会改变或更改现有数据。在映射中,我们用于...
创建数组项的浅拷贝,以确保 array1 永远不会更改。这使代码在将来更易于维护和阅读。