javascript - 将项目推送到嵌套对象数组

标签 javascript reactjs

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

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

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

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

文件对象:

{
      "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 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
      ]
    }
  }
)

关于javascript - 将项目推送到嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335534/

相关文章:

javascript - try..catch 没有捕捉到异步/等待错误

javascript - 如何删除(删除)对象数组中的特定项目

javascript - Mobx 状态树能否导致 "race conditions"/仅适用于 setTimeout?

javascript - 如何使用 HTML5-Canvas 为图像着色?

javascript - Bootstrap Popover 中的 MathJax 没有正确显示

javascript - 高效拉取未知数据,分离并以特定格式存储?

javascript - 如何在本地环境中测试共享社交媒体链接预览?

reactjs - React Native AppLoading 无需 Expo

reactjs - React componentDidMount() 在未安装的组件上被触发

javascript - 如何使用 Redux/Axios 捕获和处理错误响应 422?