TypeError: Cannot add property X, object is not extensible

This is an error that occurs when we try to add an attribute to a non-extensible object. We had a function that adds an attribute to each nested object. Following is the function code:

  const setDynamicAttr = (obj) => {
      if (typeof obj === 'object') {
          # Add an attribute here
          obj['constructor'] = undefined;  
      }

      if(obj.hasOwnProperty("props")){
          obj.props.children.map(item => {
              return setDynamicAttr(item);
          });
      }
      return obj;
  };

  # Funciton call
  setDynamicAttr(obj); // obj were non-extensible i.e. Object.preventExtensions(obj);

Solution of the issue

To solve the above issue we had to close the object to create a new object and then call the function. The cloned object was allowed to extend. Following is the code to deep clone a nested object:

const clonedObj = JSON.parse(JSON.stringify(obj));
setDynamicAttr(clonedObj);

Cloning an object involves a lot of things. It can be really complex due to functions, circular references, etc. We can very easily get from existing libraries. Some of the JavaScript utility libraries are quite standard and efficient to use.

In our project, if we already have those libraries we can easily utilize them.

lodash – cloneDeep;
AngularJS – angular.copy
jQuery – jQuery.extend(true, { }, oldObject); .clone() only clones DOM elements