user3378165
user3378165

Reputation: 6896

Push item to a nested object array

I have an object with nested objects with the below structure, how can I dynamically add new items (newData) to the cost3 array?

I have tried that but the new data isn't being pushed, what am I doing wrong?

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

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

File object:

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

Upvotes: 3

Views: 137

Answers (4)

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Your code is incorrect.

Replace [cost3] with cost3 and {} with [], like so:

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

Upvotes: 2

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You can try it using concat.

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

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

Upvotes: 0

Atul Joshi
Atul Joshi

Reputation: 15

You can use .push() method to add item to object, for dynamic addition you can iterate through the array.

Upvotes: -1

giuseppedeponte
giuseppedeponte

Reputation: 2391

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

Upvotes: 2

Related Questions