如何在不改变容器的情况下更改数组值(对象数组内)? javascript

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);