如何显示基于数组的类别子类别

时间:2019-05-27 21:17:44

标签: javascript sorting

我有一个数组,其中包含一些数据以显示类别和子类别。

{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

5 个答案:

答案 0 :(得分:2)

对于一般解决方案,您可以获取数据并实现一棵轻树类,其中每个节点都有一个值和该节点的子级列表。然后,您可以创建迭代器或类似的函数,以对树进行深度优先遍历。它可以返回深度信息,使您可以使用适当的缩进来打印值。

ev2ebitda

答案 1 :(得分:2)

您需要数据的树表示形式,因为您的数据是自引用表。因此,您需要编写代码将平面结构转换为树。例如,您可以使用以下代码执行此操作:

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>

答案 2 :(得分:2)

这可以通过递归方法来实现。

const arr = [{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"}];

const render = (arr, id) => {
  const div = document.createElement('div');
  const span = document.createElement('span');
  span.innerText = arr.find(e => e.id === id).lable;
  div.appendChild(span);
  arr.filter(e => e.parent_id === id).forEach(sub => {
    div.appendChild(render(arr, sub.id));
  });
  return div;
}

arr.filter(e => e.parent_id === "0").forEach(main =>    document.querySelector('div').appendChild(render(arr, main.id)));
div {
  margin-left: 5px;
}
<div></div>

答案 3 :(得分:1)

对于每个类别和子类别,只需使用以下过滤器功能即可:

var arr = [{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"}];

function isParent(element, index, array) {
  return (element.parent_id == "0");
}

let filtered = arr.filter(isParent);

console.log(filtered);

答案 4 :(得分:1)

首先获取一棵树,然后获取平面表示。

function getTree(array, root) {
    var o = {};
    array.forEach(payload => {
        Object.assign(o[payload.id] = o[payload.id] || {}, { payload });
        o[payload.parent_id] = o[payload.parent_id] || {};
        o[payload.parent_id].children = o[payload.parent_id].children || [];
        o[payload.parent_id].children.push(o[payload.id]);
    });
    return o[root].children;
}

function getFlat(array = []) {
    return array.reduce((r, { payload, children }) =>
        r.concat(payload, getFlat(children)), []);
}

var data = [{ 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" }],
    result = getFlat(getTree(data, '0'));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }