"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.

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

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' };
});
Share:
17,322
Evanss
Author by

Evanss

Updated on June 11, 2022

Comments

  • Evanss
    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
    Sterling Archer over 6 years
    While this is true it can cause the error, it doesn't seem to be the case here.
  • Sterling Archer
    Sterling Archer over 6 years
    You 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