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

时间:2019-10-11 06:38:35

标签: javascript reactjs

我有一个带有以下结构的嵌套对象的对象,如何将新项目(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..
        ]
      }
    }

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

您的代码不正确。

[cost3]替换为cost3,将{}替换为[],就像这样:

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

答案 2 :(得分:0)

您可以使用concat进行尝试。

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

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

答案 3 :(得分:-1)

您可以使用.push()方法向对象添加项目,要进行动态添加,可以遍历数组。