2

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.

Maciej Czarnota
  • 559
  • 2
  • 8
  • 16

2 Answers2

3

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 1
    That works!! You are the man. I would never guess that I could spread the rest of the object like this. Thank you for your help! – Maciej Czarnota Aug 11 '19 at 05:40
0

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);
raman
  • 960
  • 8
  • 18