父id 表示另一个类别 id,该类别 id是其父级。使用下面的数据集,我尝试以编程方式完成这样的结构:
| Cat Top Level 1
| Cat Top Level 2
| Cat Top Level 3
| --- Cat Top 3 Child 1
| --- Cat Top 3 Child 2
| ------ Cat Top 3 Child 2 Child 1
| --------- Cat Top 3 Child 2 Child 1 Child 1
| --- Cat Top 3 Child 3
这些对象需要合并为一个和另一个。如果将"子"类别推入其直接的"父"类别,则必须进入一个名为"子"(数组(的新属性。
数据:
const categories = [
{
id: 16,
name: "Cat Top Level 1",
parent: 0,
},
{
id: 17,
name: "Cat Top Level 2",
parent: 0,
},
{
id: 18,
name: "Cat Top Level 3",
parent: 0,
},
{
id: 19,
name: "Cat Top 3 Child 1",
parent: 18,
},
{
id: 20,
name: "Cat Top 3 Child 2",
parent: 18,
},
{
id: 22,
name: "Cat Top 3 Child 2 Child 1",
parent: 20,
},
{
id: 23,
name: "Cat Top 3 Child 2 Child 1 Child 1",
parent: 22,
},
{
id: 21,
name: "Cat Top 3 Child 3",
parent: 18,
},
{
id: 15,
name: "Uncategorized",
parent: 0,
},
];
到目前为止,我想出的代码是这样的。
function mergeCategories(categories) {
categories.map((category) => {
category.children = [];
if (category.parent === 0) {
return;
}
categories.map((subCategory) => {
if (subCategory.id !== category.parent) {
return;
}
});
});
}
循环中的循环将返回许多重复项。我猜似乎也需要一个 .filter((。由于性能原因,.forEach(( 被排除在外。
到目前为止,它还不完整,当然也不起作用。当我考虑如何处理这个问题时,我的头脑都快疯了。我以为会很简单。但说实话很难。
您可以使用递归方法和reduce
方法执行此操作,该方法将检查pid
参数是否等于当前元素的id
,如果是,则将该对象添加到累加器值中。然后,您还创建递归调用来获取子对象,如果找到子项,则将它们作为子属性添加到当前对象。这也将期望根对象的值为 0parent
。
const data = [{"id":16,"name":"Cat Top Level 1","parent":0},{"id":17,"name":"Cat Top Level 2","parent":0},{"id":18,"name":"Cat Top Level 3","parent":0},{"id":19,"name":"Cat Top 3 Child 1","parent":18},{"id":20,"name":"Cat Top 3 Child 2","parent":18},{"id":22,"name":"Cat Top 3 Child 2 Child 1","parent":20},{"id":23,"name":"Cat Top 3 Child 2 Child 1 Child 1","parent":22},{"id":21,"name":"Cat Top 3 Child 3","parent":18},{"id":15,"name":"Uncategorized","parent":0}]
function toNested(data, pid = 0) {
return data.reduce((r, e) => {
if (pid == e.parent) {
const object = { ...e }
const children = toNested(data, e.id);
if (children.length) {
object.children = children
}
r.push(object)
}
return r;
}, [])
}
const result = toNested(data);
console.log(result)
有一个addChild
方法,它将找到parent
(递归(并附加到子项。
const tree = { id: 0, name: "root", children: [] };
const addChild = (obj, parent) => {
if (obj.parent === parent.id) {
parent.children.push({...obj, children: []});
} else {
parent.children.forEach((item) => addChild(obj, item));
}
};
const buildTree = (arr) => arr.forEach(obj => addChild(obj, tree));
const categories = [{"id":16,"name":"Cat Top Level 1","parent":0},{"id":17,"name":"Cat Top Level 2","parent":0},{"id":18,"name":"Cat Top Level 3","parent":0},{"id":19,"name":"Cat Top 3 Child 1","parent":18},{"id":20,"name":"Cat Top 3 Child 2","parent":18},{"id":22,"name":"Cat Top 3 Child 2 Child 1","parent":20},{"id":23,"name":"Cat Top 3 Child 2 Child 1 Child 1","parent":22},{"id":21,"name":"Cat Top 3 Child 3","parent":18},{"id":15,"name":"Uncategorized","parent":0}]
buildTree(categories);
console.log(tree);