带有父ID的单元的分层json

带有父ID的单元的分层json,第1张

带有父ID的单元的分层json

尝试类似的东西

var arry = [{ "Id": "1", "Name": "abc", "Parent": "", "attr": "abc" },    { "Id": "2", "Name": "abc", "Parent": "1", "attr": "abc" },    { "Id": "3", "Name": "abc", "Parent": "2", "attr": "abc" },    { "Id": "4", "Name": "abc", "Parent": "2", "attr": "abc" }];function convert(array){    var map = {};    for(var i = 0; i < array.length; i++){        var obj = array[i];        obj.items= [];        map[obj.Id] = obj;        var parent = obj.Parent || '-';        if(!map[parent]){ map[parent] = {     items: [] };        }        map[parent].items.push(obj);    }    return map['-'].items;}var r = convert(arry)

演示小提琴

结果

[{    "Id" : "1",    "Name" : "abc",    "Parent" : "",    "attr" : "abc",    "children" : [{     "Id" : "2",     "Name" : "abc",     "Parent" : "1",     "attr" : "abc",     "children" : [{      "Id" : "3",      "Name" : "abc",      "Parent" : "2",      "attr" : "abc",      "children" : []  }, {      "Id" : "4",      "Name" : "abc",      "Parent" : "2",      "attr" : "abc",      "children" : []  }] }]}]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5175170.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存