简体   繁体   中英

How to modify an inner property of a nested object in Javascript using a variable reference

In React, I want to set an inner property of an object stored in a state.

Suppose the following:

const myIndex = 0;
const [myobject, setmyobject] = useState({ 
  a: {
    b: [ 
      {c: 1}, 
      {c: 2} 
    ] 
  }
})

I want to modify myobject, replacing c with 3 in the first object of the b array.

So I want to do this:

setmyobject({...myobject, a.b[myIndex].c: 3});

But it gives me an error, : or, expected in the first [ .

Is this forbidden?

在此处输入图像描述

Unfortunately, doing an immutable update like that in an object literal is a bit verbose:

setmyobject({
  ...myobject,
  a: {
    ...myobject.a,
    b: myobject.a.b.map((val, idx) => 
      idx === myIndex
        ? { ...val, c: 3 }
        : val
    )
  }
});

Libraries like lodash have some functionality you might find useful like _.set , which lets you pass in a property path. Another approach could be to deep clone the object and mutate it, but the above pattern works ok if you don't want the burden of heavy libraries.

I think this would be best practice: https://github.com/kolodny/immutability-helper

import update from 'immutability-helper';
const updatedMyObject = update(myObject, {
    a: {b: {[myIndex]: {c: {$set: 3}}}}
});
setmyobject(updatedMyObject);

I don't see any reason why do you need to do it exactly in 1 string of code. Just copy object as you do it: const obj2 = {...obj1}

and then set the property you want:

obj2.ab[myIndex].c = 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM