Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is not extensible error when creating new attribute for array of objects

I have a function that needs to extend a javascript array, including a new attribute called selected:

export const initSelect = (data) => {      let newData = data.concat();     newData.map((item) => {         item.selected = false;     })      return newData; } 

data is a ReactJS state value (comes from this.state.data when calling the function), but this didn't seem to be a problem as newData is a new copy of data array...

I'm getting the following error:

TypeError: Cannot add property selected, object is not extensible 
like image 664
Mendes Avatar asked Aug 21 '17 13:08

Mendes


People also ask

How do you fix an object is not extensible?

To fix this error, you will either need to remove the call to Object. preventExtensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.

Is JavaScript arrays are extensible?

Built-in classes like Array, Map and others are extendable also.


1 Answers

You probably need to copy the objects:

export const initSelect = (data) => {  return data.map((item) => ({      ...item,      selected: false         })); } 
like image 89
Jonas Wilms Avatar answered Sep 19 '22 08:09

Jonas Wilms