当我需要深入研究数据结构时,尤其是在我的 Redux reducer 中,我经常发现自己遵循这种模式:
state.items = state.items.map((item) => {
item.subItems = item.subItems.map((subItem) => {
subItem.bottomItems = subItem.bottomItems.map((bottomItem) => {
// do something with bottomItem...
bottomItem.foo = 'bar';
return bottomItem;
});
return subItem;
});
return item;
});
这看起来像是很多样板文件,需要深入到 bottomItems
级别。
ES6 或 ES7 是否提供了一些语法糖来缓解这种模式?
最佳答案
我要提到的第一件事是您那里的代码修改了原始状态。维持state immutability principle在 redux 中,您只想返回新对象,而不是修改现有对象。
就更简单的语法而言,如果使用arrow functions和 object spread ,这种模式还不错:
return {
items: state.items.map(item => ({
...item,
subItems: item.subItems.map(subItem => ({
...subItem,
bottomItems: subItem.bottomItems.map(bottomItem => ({
...bottomItem,
foo: 'bar' // update foo to 'bar' for every bottomItem in every subItem in every item
})
})
})
}
请注意,对象传播还不是该语言的一部分,它目前是第 3 阶段提案,并且可能会成为下一个 ECMAScript 版本之一的一部分。因此,您必须使用 Babel 之类的工具对其进行转译,才能在当今的浏览器中工作。
如果您不想这样做并希望立即使用 native 可用的功能,您可以使用 Object.assign相反:
return {
items: state.items.map(item => Object.assign({}, item, {
subItems: item.subItems.map(subItem => Object.assign({}, subItem, {
bottomItems: subItem.bottomItems.map(bottomItem => Object.assign({}, bottomItem, {
foo: 'bar' // update foo to 'bar' for every bottomItem in every subItem in every item
})
})
})
}
由于您似乎想要更清晰、更具可读性的语法,因此我建议选项 1 :)
关于javascript - 深入研究多嵌套数组语法糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44310325/