我得到一个json结构,下面给出一个api,它包含一个数组形式的相关子路径。 例如,这是我的json结构
[
{
"name": "Children C1",
"path": [
"A",
"B",
"C"
]
},
{
"name": "Children C2",
"path": [
"A",
"B",
"C"
]
},
{
"name": "Children C3",
"path": [
"A",
"B",
"C"
]
},
{
"name": "Children B1",
"path": [
"A",
"B"
]
},
{
"name": "Children B2",
"path": [
"A",
"B"
]
},
{
"name": "Children A1",
"path": [
"A"
]
},
{
"name": "Children E1",
"path": [
"D",
"E"
]
}
]
这里路径是孩子们的路线。例如,第一个对象意味着 -一个 -B -C - Childeren C1
等等。我正在使用只需要这种结构的树视图库
var tree=[
{
'Name': 'A',
'children': [
{
Name: '',
children: [
]
}
]
}
]
等等。我想将我的路径结构转换为树。需要帮助我可以用普通的javasript实现这一点。
由于
答案 0 :(得分:1)
var result=input.reduce((obj,el)=>{
var orig=obj;
for(key of el.path){
var found=obj.find(e=>e.name===key);
if(found){
obj=found.children;
}else{
var temp={name:key, children:[]};
obj.push(temp);
obj=temp.children;
}
}
obj.push(el.name);
return orig;
},[]);
http://jsbin.com/cowowisaji/edit?console
它创建了以下结构:
[{
name:"A",
children:[
"Children A1",
{name:B", children:[...]}
]
}]
它只是迭代所有元素并通过搜索数组中的正确路径对象来解析路径,如果路径元素不存在则创建它。
上面的代码可以简化为:
var result=input.reduce((obj,el)=>(el.path.reduce((path,name)=>(path.find(e=>e.name==name)||(path[path.length]={name:name,children:[]})).children,obj).push(el.name),obj),[]);
答案 1 :(得分:1)
另一种方法是使用辅助对象来保持对命名对象的引用。
var data = [{ name: "Children C1", path: ["A", "B", "C"] }, { name: "Children C2", path: ["A", "B", "C"] }, { name: "Children C3", path: ["A", "B", "C"] }, { name: "Children B1", path: ["A", "B"] }, { name: "Children B2", path: ["A", "B"] }, { name: "Children A1", path: ["A"] }, { name: "Children E1", path: ["D", "E"] }],
tree = function (array) {
var result = [],
o = { _: result };
array.forEach(function (a) {
a.path.concat(a.name).reduce(function (r, b) {
if (!r[b]) {
r[b] = { _: [] };
r._.push({ name: b, children: r[b]._ });
}
return r[b];
}, o);
});
return result;
}(data);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }