我正在尝试将键“greeting”添加到对象数组中。我的代码按预期添加 key ,但唯一的问题是,当我控制台日志时,它在底部添加另一个数组。
function greetDevelopers(list) {
list.greeting = list.map(x => x.greeting = `Hi ${x.firstName}, what do
you like most about ${x.language}?` );
console.log(list);
};
它返回以下内容
[ { firstName: 'Sofia',
lastName: 'I.',
country: 'Argentina',
continent: 'Americas',
age: 35,
language: 'Java',
greeting: 'Hi Sofia, what do you like most about Java?' },
{ firstName: 'Lukas',
lastName: 'X.',
country: 'Croatia',
continent: 'Europe',
age: 35,
language: 'Python',
greeting: 'Hi Lukas, what do you like most about Python?' },
{ firstName: 'Madison',
lastName: 'U.',
country: 'United States',
continent: 'Americas',
age: 32,
language: 'Ruby',
greeting: 'Hi Madison, what do you like most about Ruby?' },
greeting: [ 'Hi Sofia, what do you like most about Java?',
'Hi Lukas, what do you like most about Python?',
'Hi Madison, what do you like most about Ruby?' ] ]
有关如何将问候语保留在每个对象中但从末尾删除的任何建议。将不胜感激。
谢谢
最佳答案
您不应该分配给 list.greeting
- 将结果分配给数组(您在数组末尾看到的新属性 - 数组不应该有这样的属性,只有元素)。您想要的只是副作用(而不是新数组),因此您应该使用 forEach
而不是 map
(并且不要将结果分配给任何内容 - 只需记录再次数组):
const input = [ { firstName: 'Sofia',
lastName: 'I.',
country: 'Argentina',
continent: 'Americas',
age: 35,
language: 'Java',
}, { firstName: 'Lukas',
lastName: 'X.',
country: 'Croatia',
continent: 'Europe',
age: 35,
language: 'Python',},
{ firstName: 'Madison',
lastName: 'U.',
country: 'United States',
continent: 'Americas',
age: 32,
language: 'Ruby',
}];
function greetDevelopers(list) {
list.forEach((item) => {
item.greeting = `Hi ${item.firstName}, what do you like most about ${item.language}?`;
});
console.log(list);
}
greetDevelopers(input);
关于javascript - 在 JavaScript 中向对象数组添加键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220462/