尝试类似的东西
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" : [] }] }]}]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)