向 Javascript 对象数组中的对象添加新属性
我正在尝试向作为对象数组一部分的对象添加新属性。 主数组如下所示:
0: {key: 'Fruits', props: Array(22)}
1: {key: 'Dried', props: Array(1)}
2: {key: 'Fresh', props: Array(1)}
3: {key: 'Exotic', props: Array(6)}
4: {key: 'Nuts', props: Array(6)}
我想要修改的是 props 键内的一个对象。当单击与名称匹配的某个对象时,应添加新属性。所以我的代码如下所示:
let updatedFruitsArr = [];
const fruitsArr = [...getFruitsFromLocalStorge()];
// modify the fruits array in order to add a new key to the
// object that matches the name selected
fruitsArr.forEach((fruits) => {
updatedFruitsArr.push({
...fruits,
props: [...fruits.props].map((fruit) => {
if (fruit.name === fruitName) {
return {
...fruit,
isInCart: true
};
} else {
return fruit
}
}),
});
});
但是,每次 updatedFruitsArr 返回原始数组时未添加该属性。 你能告诉我我做错了什么吗? 谢谢
I am trying to add a new property to an object which is part of an array of objects.
The main array looks like this:
0: {key: 'Fruits', props: Array(22)}
1: {key: 'Dried', props: Array(1)}
2: {key: 'Fresh', props: Array(1)}
3: {key: 'Exotic', props: Array(6)}
4: {key: 'Nuts', props: Array(6)}
What I want to modify is an object inside props key. It is when clicking upon a certain object that matches the name that new property should be added. So my code looks like this:
let updatedFruitsArr = [];
const fruitsArr = [...getFruitsFromLocalStorge()];
// modify the fruits array in order to add a new key to the
// object that matches the name selected
fruitsArr.forEach((fruits) => {
updatedFruitsArr.push({
...fruits,
props: [...fruits.props].map((fruit) => {
if (fruit.name === fruitName) {
return {
...fruit,
isInCart: true
};
} else {
return fruit
}
}),
});
});
However, every time updatedFruitsArr returns the original array without that property added.
Could you please tell me what I am doing wrong?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要创建新数组并使用
.forEach
和.push
,只需使用.map
即可:You don't need to create a new array and use
.forEach
and.push
, you can just use.map
: