How to update properties of an array nested inside objects in ReactJS

Mohammed Shirhaan :

I have simplified my large data set as follows,

let state = {
    someProp: {
        someOtherProp: [
            {
                key1: "value1",
                key2: "value2"
            },
            {
                key1: "value3",
                key2: "value4"
            }
        ]
    }
}

I want to update the key1 prop of 0th index of someOtherProp, say to "value5".

Tried the following

let newState = {
    ...state, 
        someProp: 
            {...state.someProp, 
                someOtherProp: 
                    {...state.someProp.someOtherProp, 
                        [0]: 
                           {...state.someProp.someOtherProp[0], 
                               key1 : "value5"
                           }
                    }
            }
}

document.write(JSON.stringify(newState));

Output :

    {
       "someProp": {
          "someOtherProp": {
               "0": {
                      "key1":"value5",
                      "key2":"value2"
                    },
               "1": {
                       "key1":"value3",
                       "key2":"value4"
                    }
           }
        }
      }

But it will convert someOtherProp from array of objects to just nested array. I know that the problem is with "[0] : ..." statement. Not sure how to write it. Please help. New to JS and ReactJS.

T.J. Crowder :

You're creating an object, not an array, for someOtherProp:

someOtherProp: 
    {...state.someProp.someOtherProp, 
        [0]: 
           {...state.someProp.someOtherProp[0], 
               key1 : "value5"
           }
    }

Create an array instead. I'd do it before the big object literal:

const someOtherProp = [...state.someProp.someOtherProp];
someOtherProp[0] = {
    ...state.someProp.someOtherProp[0]
    key1 : "value5"
};

then:

const someOtherProp = [...state.someProp.someOtherProp];
someOtherProp[0] = {
    ...state.someProp.someOtherProp[0]
    key1 : "value5"
};
let newState = {
    ...state, 
        someProp: 
            {...state.someProp,  someOtherProp}
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^
}

But if you want, you can do it inline instead:

someOtherProp: 
    [
// −^   {...state.someProp.someOtherProp[0],      // Note this is first
            key1 : "value5"
        },
        ...state.someProp.someOtherProp.slice(1)  // Note skipping the first
    ]
// −^

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27265&siteId=1