"object is not extensible" error trying to add field in map function
17,322
Solution 1
Most likely the Object is marked as not extensible and you are running strict mode.
When the method Object.preventExtensions(obj)
is called, you get the error.
'use strict';
var obj = {};
Object.preventExtensions(obj);
obj.x = 'foo';
You will get the error Uncaught TypeError: Cannot add property x, object is not extensible
Solution 2
const newArray = oldArray.map(item => {
return Object.assign({}, item, { newField: 'Something' });
});
Solution 3
you could use object spread (es6 feature) like so:
const newArray = oldArray.map(item => {
// { ...item } creates a new object and spreads all of "item" items
// into it. We can then assign a "newField" or overwrite "newField"
// if it already exists on "item"
return { ...item, newField: 'something' };
});
Author by
Evanss
Updated on June 11, 2022Comments
-
Evanss about 2 years
Im trying to add a new field to items in an array with map:
const newArray = oldArray.map(item => { return (item.newField = 'Something'); });
And Ive tried:
const newArray = oldArray.map(item => { item.newField = 'Something'; return item; });
However I get an error:
TypeError: Cannot add property newField, object is not extensible
-
Sterling Archer over 6 yearsWhile this is true it can cause the error, it doesn't seem to be the case here.
-
Sterling Archer over 6 yearsYou don't need to use const and return here,
Object.assign({}
returns a shallow clone, and a single line lamba (arrow function) has an implied return