【问题标题】:How to copy nested object properties using spread operator如何使用扩展运算符复制嵌套对象属性
【发布时间】:2021-07-07 20:12:48
【问题描述】:

我有一个对象数组,每个对象都有这些值

 id: "53ed5e27-23a5-4a06-b53f-d0113d607fb5"
measure:
units: Array(2)
0: {perPortion: 15, name: "tbsp"}
1: {perPortion: 1, name: "ml"}

我正在遍历数组并将点击函数传递给按钮。

function handleClick(index: number, ingredient: Data) {
    //copy original array
    const newListArr = [...props.data];

    newListArr[index] = {
        ...newListArr[index],
      }

}

函数获取点击对象的索引。我正在复制循环数组,然后尝试使用扩展运算符来引入所有属性。

我的问题是我不知道如何对嵌套对象使用扩展运算符。

我只想获取单位数组中“perPortion”键的值而不影响其他任何内容。 我该怎么做?

提前感谢您的帮助!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我只想获取目标中“perPortion”键的值 单位数组而不影响其他任何东西。

    您可以复制整个嵌套对象,然后覆盖特定键的值。您将需要浅拷贝所有正在更新的嵌套属性。

    function handleClick(index: number, ingredient: Data) {
      const newItem = {
        // shallow copy data
        ...props.data,
        measure: {
          // shallow copy measure object
          ...props.data.measure,
          // copy units array
          units: props.data.measure.units.map((unit, i) =>
            i === index
              ? {
                  // shallow copy specific unit at matched index
                  ...unit,
                  perPortion: // new per portion value
                }
              : unit
          )
        }
      };
    
      .... // return or use newItem
    }
    

    【讨论】:

    • 感谢@Drew 的评论,我做到了,但关键 PerPortion 只是被添加到整个对象中,而不是被覆盖
    • 理想情况下,我只想定位第一个对象units[0].perPortion中的“perPortion”键
    • @Whyudodis 这意味着 perPortion 属性在以前的数组对象中不存在,将被覆盖。您能否分享一个您的实际数据示例,以及您具体尝试更新的 perPortion 属性是什么?
    • perPortion 仅存在于数组的“units”中,而“units”则存在于对象的“measure”中。非常感谢您的宝贵时间
    • @Whyudodis 不用担心。你能分享一下外部对象是什么吗?它只是一个对象还是 some 数组的一部分?处理程序中的index 是您要更新的嵌套units 数组的索引吗?
    猜你喜欢
    • 2020-03-18
    • 2021-01-15
    • 2020-03-15
    • 1970-01-01
    • 2020-06-09
    • 2017-06-12
    • 1970-01-01
    • 2020-11-21
    • 2017-09-20
    相关资源
    最近更新 更多