gpt4 book ai didi

javascript - 在javascript中向对象数组添加一个键

转载 作者:行者123 更新时间:2023-11-29 18:51:32 27 4
gpt4 key购买 nike

我正在尝试将键“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 - 它将结果分配给 array(您在数组末尾看到的新属性 - arrays不应该有这样的属性,只有元素)。你想要的只是副作用(不是新数组),所以你应该使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com