gpt4 book ai didi

javascript - 从 JSON 对象数组构建树

转载 作者:太空宇宙 更新时间:2023-11-03 23:11:45 26 4
gpt4 key购买 nike

给定以下 JSON 数组:

    [{"ID":12,"NAME":"ktc","PARENTID":0},
{"ID":11,"NAME":"root","PARENTID":0},
{"ID":1,"NAME":"rwhitney","PARENTID":0},
{"ID":21,"NAME":"shared folder","PARENTID":0},
{"ID":2,"NAME":".config","PARENTID":1},
{"ID":5,"NAME":"wallpapers","PARENTID":1},
{"ID":3,"NAME":"geany","PARENTID":2},
{"ID":4,"NAME":"colorschemes","PARENTID":3},
{"ID":13,"NAME":"efast","PARENTID":12},
{"ID":15,"NAME":"includes","PARENTID":13},
{"ID":14,"NAME":"views","PARENTID":13},
{"ID":17,"NAME":"css","PARENTID":15},
{"ID":16,"NAME":"js","PARENTID":15}]

我需要构建一个菜单树,其中的子文件夹嵌套在父文件夹下。

这是一些服务器端代码:

    socket.on('get-folders', function(data){
var folders = [];
getSession(session.key, function(currSession){
db.rows('getFolders', currSession, [currSession.user], function(err, rows){
if (err) {
socket.emit('err', 'Error is: ' + err );
} else if(rows[0]){
//~ folders.push(JSON.stringify(rows));
socket.emit('get-folders', JSON.stringify(rows));
//~ n_Folders(rows, currSession, socket, folders, 0);
}
});
});
});

和客户端:

    function rtnSocket(cmd, data, cb){
socket.emit(cmd, data);
socket.on(cmd, cb);
}

rtnSocket('get-folders', folderid, function(data){
console.log(data);
});

有人可以帮助指导我正确的方向吗?

最佳答案

您可以从平面数据结构中收集所有 Node ,使用 IDPARENTID 作为哈希表中的键,并获取根数组作为结果。

var data = [{ ID: 12, NAME: "ktc", PARENTID: 0 }, { ID: 11, NAME: "root", PARENTID: 0 }, { ID: 1, NAME: "rwhitney", PARENTID: 0 }, { ID: 21, NAME: "shared folder", PARENTID: 0 }, { ID: 13, NAME: "efast", PARENTID: 12 }, { ID: 2, NAME: ".config", PARENTID: 1 }, { ID: 5, NAME: "wallpapers", PARENTID: 1 }, { ID: 15, NAME: "includes", PARENTID: 13 }, { ID: 14, NAME: "views", PARENTID: 13 }, { ID: 3, NAME: "geany", PARENTID: 2 }, { ID: 17, NAME: "css", PARENTID: 15 }, { ID: 16, NAME: "js", PARENTID: 15 }, { ID: 4, NAME: "colorschemes", PARENTID: 3 }],
tree = function (data, root) {
var t = {};
data.forEach(o => {
Object.assign(t[o.ID] = t[o.ID] || {}, o);
t[o.PARENTID] = t[o.PARENTID] || {};
t[o.PARENTID].children = t[o.PARENTID].children || [];
t[o.PARENTID].children.push(t[o.ID]);
});
return t[root].children;
}(data, 0);

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

关于javascript - 从 JSON 对象数组构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com