Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, adding elements to array inside another array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

what can I do?

>Solution :

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"
      }
    ]
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading