我有
const abc = {
main: {
primary: 'initialPrimary',
},
buttons: {
text: 'initialText',
},
}
const updateAbc = (node, key, value) => {
return {updated abc}
}
如果我调用updateAbc('main','primary','updatedPrimary')
,它应该返回更新后的abc对象
{
main: {
primary: 'updatedPrimary',
},
buttons: {
text: 'initialText',
},
}
或者当调用updateAbc('buttons','text','updatedText')
时,它应该返回值为
{
main: {
primary: 'initialPrimary',
},
buttons: {
text: 'updatedText',
},
}
它应该只更新传递的值。如何在es6中实现?
const abc = {
main: {
primary: 'initialPrimary',
},
buttons: {
text: 'initialText',
},
}
const updateAbc = (node, key, value) => {
return {
...abc,
[node]: {
[key]: value
}
}
}
请注意,这不会检查不存在的节点或键。
你特别要求用es6,所以我就用它来回答。这是通过扩展abc
,然后动态地使用node
和key
来提供更新值的路径来实现的。
通过使用Object.assign
,您可以通过以下操作获得相同的结果:
const updateAbc = (node, key, value) => {
var copyAbc = Object.assign({},abc)
copyAbc[node][key] = value
return copyAbc
}
如果给定不存在的node
名称