0

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?

1
  • what is 'projectData.myArr'? does myArr contains the array ? Commented Dec 9, 2021 at 17:09

2 Answers 2

3

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,
  }));
}));
Sign up to request clarification or add additional context in comments.

Comments

0

One can also try using the Native StructuredClone or lodash cloneDeep(for node version before V17.2.0)

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

This will create a new clone thus none of the property in redux will be modified allowing one to freely work with the code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.