我想要理解以下示例,以便我能够非常清楚地了解它。不幸的是,我的脑子卡在这一行上:.forEach (c => (node[c.id] = makeTree(categories, c.id))). 有人可以给我一个提示吗?
let categories = [
{ id: 'animals', parent: null },
{ id: 'mammals', parent: 'animals' },
{ id: 'cats', parent: 'mammals' },
{ id: 'dogs', parent: 'mammals' },
{ id: 'chihuahua', parent: 'dogs' },
{ id: 'labrador', parent: 'dogs' },
{ id: 'persian', parent: 'cats' },
{ id: 'siamese', parent: 'cats' }
];
let makeTree = (categories, parent) => {
let node = {};
categories
.filter(c => c.parent == parent)
.forEach(c => (node[c.id] = makeTree(categories, c.id)));
return node;
};
console.log(makeTree(categories, null));
expected:
{
animals: {
mammals: {
dogs: {
chihuahua: null
labrador: null
},
cats: {
persian: null
siamese: null
}
}
}
}
filter
之后创建了一个剩余类别的子树。 - Sebastian Simon