Home > database >  React, adding elements to array inside another array
React, adding elements to array inside another array

Time:12-31

I have an array of objects like this:

{
      pksites: number;
      rooms: Room[];
}

And I'm trying to add the rooms to that array, here is what i do:

arrayOfObjects.forEach((s) => {
      s.rooms.push(...s.rooms, //new object from here{
        pkrooms: 1, 
        roomname: "Test room",
      })
    })

and the error i get is

TypeError: Cannot add property 0, object is not extensible at Array.push (<anonymous>)

what can I do?

CodePudding user response:

I think this work for you may be,

let arrayOfObjects = [{
  pksites: 1,
  rooms: []
}]


arrayOfObjects.forEach((s) => {
  s.rooms.push(...s.rooms, //new object from here
    {
      pkrooms: 1,
      roomname: "Test room",
    }
  )
})
console.log(JSON.stringify(arrayOfObjects));

output

[
  {
    "pksites": 1,
    "rooms": [
      {
        "pkrooms": 1,
        "roomname": "Test room"
      }
    ]
  }
]
  • Related