[英]Javascript: Change the value of an element in an array without mutating the array
[英]How can I change array value(inside array of objects) without mutating the container? javascript
我想要实现的是在这种情况下,当名称为“Mario”时,用 arr 的值填充数组“presents”,我得到的是数组“present”修改,但我想要的是一个非可变数组,只改变空数组的值与另一个数组的值(在这种情况下,我以 arr 为例)
let present= [
{
name: "Peter",
presents: []
},
{
name: "Mario",
presents: []
},
{
name: "Amanda",
presents: []
},
{
name: "David",
presents: []
}
]
arr = ["car","coal"]
const res= present.map(s =>s.name == "Mario" ? s.presents.concat(arr) : [])
console.log(res)
我想得到什么:
let present= [
{
name: "Peter",
presents: []
},
{
name: "Mario",
presents: ["car","coal"]
},
{
name: "Amanda",
presents: []
},
{
name: "David",
presents: []
}
]
pd:对不起,我无法解释得更好,还在学习英语。
您可以传播对象并添加所需的数组。
const present = [{ name: "Peter", presents: [] }, { name: "Mario", presents: [] }, { name: "Amanda", presents: [] }, { name: "David", presents: [] } ], array = ["car", "coal"], result = present.map(({ presents, ...o }) => ({...o, presents: [...presents, ...(o.name === "Mario"? array: [])] })); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
您可以使用 reduce() 执行以下操作,
const present = [{ name: "Peter", presents: [] }, { name: "Mario", presents: [] }, { name: "Amanda", presents: [] }, { name: "David", presents: [] } ], arr = ["car", "coal"], res = present.reduce((prev, curr) => { if(curr.name === 'Mario') { prev.push({...curr, presents: [...curr.presents, ...arr]}) } else { prev.push(curr); } return prev; }, []); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.