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
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' };
});
const newArray = oldArray.map(item => {
return Object.assign({}, item, { newField: 'Something' });
});
Most likely the Object is marked as not extensible and you are running strict mode.
Look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible
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
Alternatively you could also clone the object via Object.create(...)
const object1 = {
foo: 'foo'
};
// This will prevent extending this object:
Object.preventExtensions(object1);
const object2 = Object.create(object1);
/**
* This cloned object has no preventExtensions flag
* and can thus be extended as you like
*/
object2.bar = 'bar';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With