【发布时间】:2019-04-20 23:25:54
【问题描述】:
我是 es6 的新手,想要展平我的树对象。 (我使用的是回流——不是 redux——但扁平状态在回流中也是一个好主意)
api 响应:
export const node = {
item: 1,
children: [
{
item: 2,
children: [
{
item: 3,
children: [
{
item: 4,
children: []
},
{
item: 5,
children: []
},
{
item: 6,
children: [
{
item: 7,
children: []
},
{
item: 8,
children: []
},
{
item: 9,
children: []
}
]
}
]
},
{
item: 10,
children: [
{
item: 11,
children: []
},
{
item: 12,
children: [
{
item: 13,
children: []
},
{
item: 14,
children: []
}
]
}
]
}
]
}
]
}
我的目标是:
tree= {
byId: {
item1 : {
id: 'item1',
name: 'item1', parent: null,
children : ['item2']
}
}
parent 是一个 id,childrend 是 id 数组
用于构建面包屑(使用父对象)或列出子对象...
使用
从 id 获取对象tree.byId[someId]
我最后一次尝试使用带有 es6 扩展运算符的递归函数:
const flattenTree = (tree, flattenTree) => {
if (node.children.length) {
node.children.map(child => {
return flattenTree(child, [...tree= { id: child.item}])
})
} else {
return [...tree, tree.byId[cat.item] = { id: cat.item, name: cat.item }]
}
}
对不起,我是第一次来这里,所以我的帖子格式不太好......
感谢帮助
【问题讨论】:
-
您希望所有 id 都位于根目录,例如 tree : { byId: { item1: {...}, item2: {...}, item3: {...}, .... , item14:{...}}}?
标签: javascript recursion ecmascript-6 flatten arrow-functions