Ошибка изменения состояния выдается, когда я пытаюсь изменить свойство в одном массиве объектов на основе другого массива объектов

#javascript #reactjs #ecmascript-6

#javascript #reactjs #ecmascript-6

Вопрос:

У меня есть 2 массива объектов, один по умолчанию, а другой сохраняется в локальном состоянии.

 Array 1
DefaultArray =  
[{type: typeA, isImportant: true, Content: ContentDefaultforA}, {type: typeB, isImportant: true, Content1: ContentDefaultforB1, Content2: ContentDefaultforB2}, {type: typeC, isImportant: false, Content: ContentDefaultforC}, {type: typeD, isImportant: false, Content: ContentDefaultforD}]
 

Значение

 this.state.newArray = 
[{type: typeB, isImportant: true, Content1: ContentDefaultforB1, Content2: ContentDefaultforB2}, {type: typeA, isImportant: true, Content: ModifiedContentForA}, {type: typeD, Content: ModifiedCOntentForD, isImportant: true}, {type: typeC, isImportant: true, Content: ModifiedCOntentForC}]
 

Я хочу сравнить 2 массива и изменить свойство isImportant в this.state.newArray на то, что в массиве по умолчанию
Итак, результат, который я хочу

 this.state.newArray = 
[{type: typeB, isImportant: true,, Content1: ContentDefaultforB1, isImportant: true, Content2: ContentDefaultforB2}, {type: typeA, isImportant: true, Content: ModifiedContentForA}, {type: typeD, Content: ModifiedCOntentForD, isImportant: false}, {type: typeC, isImportant: false, Content: ModifiedCOntentForC}]
 

Я делаю это

 let arrayCopy = [...this.state.newArray]
arrayCopy.forEach(item=>{
            let isImportant = defaultArray.filter(defaultItem=>defaultItem.type===item.type)[0].isImportant
            item.isImportant = isImportant
        })
 

Это вызывает изменение состояния

Как это можно исправить? Кроме того, есть ли более простой способ сделать это с помощью Lodash

Комментарии:

1. Вы (поверхностно) копируете массив, но не копируете объект, .isImportant свойство которого вы изменяете.

2. пожалуйста, сделайте фрагмент этого, используя codesandbox