【问题标题】:How can I change array value(inside array of objects) without mutating the container? javascript如何在不改变容器的情况下更改数组值(对象数组内部)? javascript
【发布时间】:2021-04-14 11:54:10
【问题描述】:

我想要实现的是在这种情况下,当名称为“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:抱歉,我无法解释得更好,还在学习英语。

【问题讨论】:

    标签: javascript arrays loops object mutation


    【解决方案1】:

    你可以使用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);

    【讨论】:

      【解决方案2】:

      您可以分散对象并添加所需的数组。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-26
        • 2018-03-25
        • 2019-02-03
        • 1970-01-01
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 2018-01-24
        相关资源
        最近更新 更多