简体   繁体   中英

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. In this example id is a dynamic value for each input in my forms. 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:

 "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. Is there a way to do it? I appreciate any advice on this.

You need to reference object at particular 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.

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:

 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);

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