gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:33:28 25 4
gpt4 key购买 nike

我正在尝试 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 持有的对象。有办法吗?我很感激对此的任何建议。

最佳答案

你需要引用特定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)

关于javascript - 具有计算对象属性名称的嵌套对象解构 - react 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com