【问题标题】:Push item to a nested object array将项目推送到嵌套对象数组
【发布时间】:2019-10-11 06:38:35
【问题描述】:

我有一个具有以下结构的嵌套对象的对象,如何将新项目 (newData) 动态添加到 cost3 数组?

我试过了,但是新数据没有被推送,我做错了什么?

const [file, setFile] = useState({})

setFile(file=> ({
      ...file,
      [cost3]: {
          ...file.cost3,
          newData
      }
}))

File对象:

{
      "info": {

      },
      "client": {

      },
      "costs": {
        "cost1": 1,
        "cost2": 5,
        "cost3": [
          {
            "a": "test",
            "b": "test",
            "c": "test",
          },
          {
            "d": "test",
            "e": "test",
            "f": "test",
          },
         //etc..       
        ],
        "cost4": [
          {
            "l": "test",
            "n": "test",
            "m": "test",
          },
        //etc..
        ]
      }
    }

【问题讨论】:

  • setFile 中的[const3] 是什么,我没有看到你在任何地方定义了 const3 变量。

标签: javascript reactjs


【解决方案1】:

const file = {
  "info": {

  },
  "client": {

  },
  "costs": {
    "cost1": 1,
    "cost2": 5,
    "cost3": [{
        "a": "test",
        "b": "test",
        "c": "test",
      },
      {
        "d": "test",
        "e": "test",
        "f": "test",
      },
      //etc..       
    ],
    "cost4": [{
        "l": "test",
        "n": "test",
        "m": "test",
      },
      //etc..
    ]
  }
}

const newData = { x: 'I am new' }

console.log(
  {
    ...file,
    costs: {
      ...file.costs,
      cost3: [
        ...file.costs.cost3,
        newData
      ]
    }
  }
)

【讨论】:

  • 如果您看到状态是如何初始化的 useState({}),您可以得出结论 ...file.costs.cost3, 将抛出“const3 of undefined”错误。我建议使用某种get 来减少出错的可能性。
【解决方案2】:

您的代码不正确。

[cost3] 替换为cost3,将{} 替换为[],如下所示:

setFile(file=> ({
      ...file,
      costs: {
        ...file.costs,
        cost3: [
          ...file.costs.cost3,
          newData
        ]
      }
}))

【讨论】:

  • 看起来 OP 正在尝试设置 file.const.const3 但由于文件是用 {} 初始化的,因此尝试传播 file.const.const3 会抛出,因为 const 最初是未定义的。也许更好地使用某种get
【解决方案3】:

您可以使用concat 进行尝试。

cost3 = [];
const [file, setFile] = useState({});

setFile(file => ({
  cost3: file.cost3.concat(newData),
}));

【讨论】:

  • 我建议使用 concat 而不是 push,因为 push 会改变数组。
【解决方案4】:

您可以使用.push() 方法将项目添加到对象,对于动态添加您可以遍历数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-25
    • 2019-03-28
    • 2021-11-06
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多