【发布时间】:2018-10-12 12:25:02
【问题描述】:
请说出我的英语和写作问题,我有一个 json 数据数组,我试图将其放入嵌套树结构但没有成功,希望有人能帮助我。 我的示例数据:
[ {
"id" : 1,
"name" : "Abc",
"path" : "/",
"type" : "folder"
}, {
"id" : 2,
"name" : "Xyz",
"path" : "/Abc/",
"type" : "folder"
}, {
"id" : 3,
"name" : "Pqr",
"path" : "/Abc/Xyz/",
"type" : "folder"
}, {
"id" : 4,
"name" : "Zap",
"path" : "/Abc/Xyz/Pqr/",
"type" : "folder"
},{
"id" : 5,
"name" : "file1",
"path" : "/Abc/Xyz/Pqr/",
"type" : "file"
},{
"id" : 6,
"name" : "file2",
"path" : "/Abc/Xyz/Pqr/",
"type" : "file"
},{
"id" : 7,
"name" : "file3",
"path" : "/Abc/Xyz/",
"type" : "file"
},{
"id" : 8,
"name" : "file4",
"path" : "/Abc/Xyz/Pqr/Zap/",
"type" : "file"
}
对不起,我正在使用少量大数据来正确理解,现在我想要的嵌套格式是这样的。
[{
"id" : 1,
"name" : "Abc",
"path" : "/",
"type" : "folder"
"Children":[{
"id" : 2,
"name" : "Xyz",
"path" : "/Abc/",
"type" : "folder",
"Children":[{
"id" : 3,
"name" : "Pqr",
"path" : "/Abc/Xyz/",
"type" : "folder",
"Children": [{
"id" : 4,
"name" : "Zap",
"path" : "/Abc/Xyz/Pqr/",
"type" : "folder",
"Children":[{
"id" : 8,
"name" : "file4",
"path" : "/Abc/Xyz/Pqr/Zap/",
"type" : "file"
}]
},{
"id" : 5,
"name" : "file1",
"path" : "/Abc/Xyz/Pqr/",
"type" : "file"
},{
"id" : 6,
"name" : "file2",
"path" : "/Abc/Xyz/Pqr/",
"type" : "file"
}]
},{
"id" : 7,
"name" : "file3",
"path" : "/Abc/Xyz/",
"type" : "file"
}]
}]
}
现在使用 lodash 的登录是这样的:datas = allData
const dd= [];
_.forEach(datas, function(v, k) {
let cc = {};
if (v.type == 'folder') {
cc['children'] = _.filter(datas, function(v1, k1) {
if (v.path + v.name + '/' == v1.path || v1.path.startsWith(v.path + v.name + '/')) {
return v1;
}
});
cc['name'] = v.name;
cc['type'] = v.type;
cc['id'] = v.id;
cc['path'] = v.path;
dd.push(cc);
} else {
if (v.path == '/') {
dd.push(cc);
}
}
});
但没有正确理解,我知道问题太长了,但请帮我解决这个问题。
【问题讨论】:
-
一致知道吗?如果有的话,它总是有 id、path、name、type 和 children
标签: javascript angular loops lodash angular6