我有一个由一些数据组成的数组,用于显示类别和子类别。
{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}
我想排序并显示这些数据,如下所示:
> Movie
>> Action
>>>James Bond Series
>Book
>>J.K Rowling
>>>Harry Potter Series
最佳答案
您需要数据的树表示,因为您的数据是自引用表。因此,您需要编写一段代码将平面结构转换为树。例如,您可以使用以下代码来执行此操作:
const makeTree = (array, id, parentId, parentValue) =>
array
.filter(node => {
return node[parentId] === parentValue;
})
.map(node => {
node["items"] = makeTree(array, id, parentId, node[id]);
return node;
});
其中 array
是源数组,id
- ID 字段的名称,parentId
- 保存父 ID,parentValue
- 根节点 ID。
您可以按如下方式调用此函数,从数组中创建一棵树:
const tree = makeTree(array, "id", "parent_id", "0");
其中 array
是您的源数组:
const array = [
{ id: "5", parent_id: "0", lable: "Movie" },
{ id: "20", parent_id: "5", lable: "Action" },
{ id: "15", parent_id: "43", lable: "J.K Rowling" },
{ id: "43", parent_id: "0", lable: "Book" },
{ id: "2", parent_id: "20", lable: "James Bond Series" },
{ id: "3", parent_id: "0", lable: "Music" },
{ id: "39", parent_id: "15", lable: "Harry Potter Series" }
];
生成的数组元素将包含 items
字段,该字段是子节点数组。
此后,您可以创建一个递归函数,使用 jQuery 渲染该树。例如:
const renderLevel = items => {
return $("<ul>").append(
items.map(item =>
$("<li>")
.html(item.lable)
.append(renderLevel(item.items))
)
);
};
调用它并将tree
变量传递给它:
$(() => {
$("body").append(renderLevel(tree));
});
这是一个sample .
const array = [
{ id: "5", parent_id: "0", lable: "Movie" },
{ id: "20", parent_id: "5", lable: "Action" },
{ id: "15", parent_id: "43", lable: "J.K Rowling" },
{ id: "43", parent_id: "0", lable: "Book" },
{ id: "2", parent_id: "20", lable: "James Bond Series" },
{ id: "3", parent_id: "0", lable: "Music" },
{ id: "39", parent_id: "15", lable: "Harry Potter Series" }
];
const makeTree = (array, id, parentId, parentValue) =>
array
.filter(node => {
return node[parentId] === parentValue;
})
.map(node => {
node["items"] = makeTree(array, id, parentId, node[id]);
return node;
});
const tree = makeTree(array, "id", "parent_id", "0");
console.log(JSON.stringify(tree))
const renderLevel = items => {
return $("<ul>").append(
items.map(item =>
$("<li>")
.html(item.lable)
.append(renderLevel(item.items))
)
);
};
$(() => {
$("body").append(renderLevel(tree));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
关于javascript - 如何根据数组显示类别子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332542/