Search code examples
angulartypescriptreduxreducers

Redux: Reduced - How to avoid object is not extensible error during the recursion on nested array?


I have the following array of objects with nested objects:

[
      {
        "name": "ONE",
        "properties": [
          {
             "name": "XXX"
          },
          {
             "name": "YY"
          }
        ]
      },
      {
        "name": "TWO",
        "properties": []
      }
    ]

And I am trying to add the attribute to each object recursively using map in Reducer Function. Where I am getting following exception:

TypeError: Cannot add property isChecked, object is not extensible

projectData.myArr.map((item, index) => {
  item.isChecked = false;
  item.properties.map((value, index1) => {
    value.isChecked = false;
  })
});

I tried to use Object.assign() as it was discussed here: Object is not extensible error when creating new attribute for array of objects

let newData = data.map((item) => 
    Object.assign({}, item, {selected:false})
)

But this way allows me to add attributes for only top-level objects and not to inner objects.

How could I solve with nested objects related to the Redux Pattern?


Solution

  • Use nested spread syntax to create new objects at each level of desired mutation:

    projectData.myArr.map((item, itemIndex) => ({
      ...item,
      isChecked: false,
      properties: item.properties.map((value, valueIndex) => ({
        ...value,
        isChecked: false,
      }));
    }));