简体   繁体   English

具有计算对象属性名称的嵌套对象解构 - 反应状态

[英]Nested object destructuring with computed object property names - react state

I'm trying to setState but I can't figure out how I can destructure the rest of object which has a dynamic property name.我正在尝试setState但我不知道如何解构具有动态属性名称的对象的其余部分。 In this example id is a dynamic value for each input in my forms.在这个例子中, id是我表单中每个输入的动态值。 After computing the state it looks like this:计算状态后,它看起来像这样:

{
    "inputConfig": {
        "5d4d684cadf8750f7077c739": {
            "0": "5d4d684cadf8750f7077c739",
            "isEmpty": true
        },
        "5d4d684cadf8750f7077c73c": {
            "time": "2019-08-10T12:33:42.439Z",
            "units": "f",
            "defaultValue": 6,
            "name": "Temp",
            "isEmpty": true
        }
    }
}

the dynamic id hols an object with input configuration:动态 id 包含一个具有输入配置的对象:

 "5d4d684cadf8750f7077c73c": {
        "time": "2019-08-10T12:33:42.439Z",
        "units": "f",
        "defaultValue": 6,
        "name": "Temp",
        "isEmpty": true
    }

This is the code I have tried so far:这是我到目前为止尝试过的代码:

  this.setState(prevState => ({
        ...prevState,
        inputConfig: {
            ...inputConfig,
            [id]: {
                ...[id], // gives me {0: "5d4d684cadf8750f7077c739"} instead of the object it holds
            }
        }}),() =>{
          console.log(this.state.inputConfig)
        })

I would like to desctructure the object that this id holds.我想解构这个id持有的对象。 Is there a way to do it?有没有办法做到这一点? I appreciate any advice on this.我很感激对此的任何建议。

You need to reference object at particular id您需要引用特定 id 的对象

 let obj = { "inputConfig": { "5d4d684cadf8750f7077c739": { "0": "5d4d684cadf8750f7077c739", "isEmpty": true }, "5d4d684cadf8750f7077c73c": { "time": "2019-08-10T12:33:42.439Z", "units": "f", "defaultValue": 6, "name": "Temp", "isEmpty": false } } } let id = "5d4d684cadf8750f7077c73c" let changed = { inputConfig:{ ...obj.inputConfig, [id]:{ ...obj.inputConfig[id], isEmpty: true } } } console.log(changed)

You can't destruct into dynamically named variables in JavaScript without using eval.不使用 eval 就不能在 JavaScript 中分解为动态命名的变量。

But you can get a subset of the object dynamically if you know the property name that can appear in an object, using reduce function as follows:但是,如果您知道可以出现在对象中的属性名称,则可以动态获取对象的子集,使用 reduce 函数如下:

 const destructured = (obj, ...keys) => keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {}); const object = { id: 987637, color: 'blue', amount: 10, }; const set1 = destructured(object, 'id'); const set2 = destructured(object, 'id', 'color', 'amount'); console.log(set1); console.log(set2);

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

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