let personNames = [ { firstName: 'Ben' }, {firstName : 'Bob' } ];
let details= { city: 'Dublin' , Country: 'Ireland' } ;
let nameList = [];
let nameObj = {};
for(let name of personNames){
nameObj = details;
nameObj['f_name'] = name.firstName;
nameList.push(nameObj);
}
预期产出:
[ {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}, {fname:'Bob',city:
'Dublin' , Country: 'Ireland'}]
我得到的是:
[ {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}, {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}}]
我在这里做错了什么?
答案 0 :(得分:3)
你在这里做什么是推进阵列相同的参考。您可以每次将nameObj创建到for循环中,以便引用数组中的不同对象。
let personNames = [ { firstName: 'Ben' }, {firstName : 'Bob' } ];
let nameList = [];
for(let name of personNames){
let nameObj = {};
nameObj['f_name'] = name.firstName;
nameList.push(nameObj);
}
答案 1 :(得分:1)
您可以使用Array.map方法实现它,即ES6
const personNames = [{
firstName: 'Ben',
}, {
firstName : 'Bob',
}];
const nameList = personNames.map(x => ({
f_name: x.firstName,
}));
console.log(nameList);

我们循环遍历personNames
,并且对于其中的每个元素,我们正在创建一个包含名为f_name
的键的新对象。
答案 2 :(得分:0)
nameObj应该在for循环中