1

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?

2
  • What does arrayOfObjects contain? Commented Dec 31, 2021 at 9:36
  • 1
    @kiner_shah is an array of the object I showed on top, it is like [{ pksites: 1, rooms: [] }, {pksites: 2, rooms: []}] Commented Dec 31, 2021 at 9:42

1 Answer 1

2

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"
      }
    ]
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.