我想更改与此类似的对象的属性,这是一个简化的对象,具有原始的一些属性:
state = {
pivotComuns: [
{
id: 1,
enabled : true
},
{
id: 2,
enabled : true
}
],
otherProperties : "otherProperties"
}
我正在像这样更改启用状态:
state = {
...state,
pivotColumns: {
...state.pivotColumns,
[2]: {
...state.pivotColumns[2], enabled: !state.pivotColumns[2].enabled
}
}
}
它有效,但它返回一个对象,而不是像 I 那样返回一个数组,它返回一个对象,“请注意我将 [] 更改为 {}”:
state = {
pivotComuns: {
{
id: 1
enabled : true
},
{
id: 2,
enabled : true
}
},
otherProperties : "otherProperties"
}
我做错了什么,我需要将该属性保留为一个数组。
最佳答案
很晚的帖子,但为了将来引用,您可以执行以下操作:
state = {
...state,
pivotColumns: state.pivotColumns.map(pc =>
pc.id === 2 ? {...pc, enabled:!pc.enabled} : pc
)
}
优点是您不会更改“旧数组”中引用的对象,而是在其位置插入一个新对象。因此,如果您想在该州来回走动,现在就可以这样做。
关于javascript - 使用 Spread Operator 更改数组中的属性返回对象而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120358/