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

时间:2019-08-11 04:49:57

标签: javascript reactjs setstate object-destructuring

我正在尝试setState,但是我不知道如何分解具有动态属性名称的其余对象。在此示例中,id是表单中每个输入的动态值。 计算状态后,它看起来像这样:

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

动态ID将对象配置为输入配置:

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

这是我到目前为止尝试过的代码:

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

我想解构此id所拥有的对象。有办法吗? 我对此表示感谢。

2 个答案:

答案 0 :(得分:2)

您需要以特定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)

答案 1 :(得分:0)

如果不使用eval,则无法在JavaScript中分解为动态命名的变量。

但是,如果您知道可以出现在对象中的属性名称,则可以使用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);