简体   繁体   English

如何使用变量引用在 Javascript 中修改嵌套 object 的内部属性

[英]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.在 React 中,我想设置存储在 state 中的 object 的内部属性。

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.我想修改myobject,将b数组的第一个object中的c替换为3。

So I want to do this:所以我想这样做:

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

But it gives me an error, : or, expected in the first [ .但它给了我一个错误, : or, expected在第一个[

Is this forbidden?这是禁止的吗?

在此处输入图像描述

Unfortunately, doing an immutable update like that in an object literal is a bit verbose:不幸的是,在 object 文字中进行这样的不可变更新有点冗长:

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.lodash这样的库有一些你可能会觉得有用的功能,比如_.set ,它可以让你传入一个属性路径。 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.另一种方法可能是深度克隆 object 并对其进行变异,但如果您不想要繁重的库负担,上述模式可以正常工作。

I think this would be best practice: https://github.com/kolodny/immutability-helper我认为这将是最佳实践: 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.我看不出你为什么需要在 1 串代码中完全做到这一点。 Just copy object as you do it: const obj2 = {...obj1}只需复制 object 即可: const obj2 = {...obj1}

and then set the property you want:然后设置你想要的属性:

obj2.ab[myIndex].c = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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