从对象的平面数组构建对象的树数组 [英] Building tree array of objects from flat array of objects

查看:84
本文介绍了从对象的平面数组构建对象的树数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从平面数组构建树形数组:

I want to build a tree array from flat array:

这是平面数组:

nodes = [
    {id: 1, pid: 0, name: "kpittu"},
    {id: 2, pid: 0, name: "news"},
    {id: 3, pid: 0, name: "menu"},
    {id: 4, pid: 3, name: "node"},
    {id: 5, pid: 4, name: "subnode"},
    {id: 6, pid: 1, name: "cace"}
];

NB:id =节点id; pid =父节点ID.

NB: id = node id; pid = parent node id.

我想将其转换为该数组:

I want to transform it into this array:

nodes = [{
    id: 1,
    name: 'kpittu',
    childs: [{
        id: 6,
        name: 'cace'
    }]
}, {
    id: 2,
    name: 'news'
}, {
    id: 3,
    name: 'menu',
    childs: [{
        id: 4,
        name: 'node',
        childs: [{
            id: 5,
            name: 'subnode'
        }]
    }]
}];

我试图使用递归函数来达到预期的结果,但是我正在寻找一种更好的方法.感谢您的回复.

I tried to use a recursive function to achieve the expected result, but I'm looking for a better approach. Thanks for your response.

推荐答案

您可以使用哈希表,并在每个循环中将idpid用作连接的节点.

You could use a hash table and take id and pid in every loop as connected nodes.

此建议也适用于未排序的数据.

This proposal works with unsorted data as well.

var nodes = [{ id: 6, pid: 1, name: "cace" }, { id: 1, pid: 0, name: "kpittu" }, { id: 2, pid: 0, name: "news" }, { id: 3, pid: 0, name: "menu" }, { id: 4, pid: 3, name: "node" }, { id: 5, pid: 4, name: "subnode" }],
    tree = function (data, root) {
        var r = [], o = {};
        data.forEach(function (a) {
            if (o[a.id] && o[a.id].children) {
                a.children = o[a.id] && o[a.id].children;
            }
            o[a.id] = a;
            if (a.pid === root) {
                r.push(a);
            } else {
                o[a.pid] = o[a.pid] || {};
                o[a.pid].children = o[a.pid].children || [];
                o[a.pid].children.push(a);
            }
        });
        return r;
    }(nodes, 0);

console.log(tree);

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

这篇关于从对象的平面数组构建对象的树数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆