Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"object is not extensible" error trying to add field in map function

Tags:

javascript

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
like image 629
Evanss Avatar asked Feb 28 '18 04:02

Evanss


4 Answers

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' };
});
like image 86
moto Avatar answered Nov 07 '22 10:11

moto


const newArray = oldArray.map(item => {
  return Object.assign({}, item, { newField: 'Something' });
});
like image 30
Evanss Avatar answered Nov 07 '22 12:11

Evanss


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

like image 2
randominstanceOfLivingThing Avatar answered Nov 07 '22 11:11

randominstanceOfLivingThing


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';
like image 1
jahller Avatar answered Nov 07 '22 10:11

jahller