我有一个对象数组,我想添加/更改一个新属性,因为它与type
和key
匹配。
[
{
"type": "a",
"units": [
{
"key": "keyofba"
},
{
"key": "mytargetkey"
}
]
},
{
"type": "b",
"units": [
{
"key": "keyofb"
}
]
},
{
"type": "ab",
"units": [
{
"key": "mytargetkey"
}
]
}
]
我试过这个
this.setState({
schema: schema.map(s => {
if (s.type === 'a' || s.type === 'ab') { //hardcord for testing
return s.units.map(unit => {
if (unit.key === 'mytargetkey') {
return {
...unit,
newProp: 'newProp value'
}
} else {
return { ...unit }
}
})
} else {
return { ...s }
}
})
但不知何故它不起作用,我想我错过了一些东西,需要观察员。
这是因为您必须返回在新对象内部修改的列表,如果不是目标,则按原样返回元素:
schema.map(s => {
if (s.type === 'a' || s.type === 'ab') { //hardcord for testing
return {...s, units: s.units.map(unit => {
if (unit.key === 'mytargetkey') {
return {
...unit,
newProp: 'newProp value'
}
} else {
return unit
}
})}
} else {
return s
}
})