I am getting a json structure given below form an api which contains paths of related children in an array form . for example here is my json structure
[
{
"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"
]
}
]
Here path is the route for a childeren. For example first object means -A -B -C - Childeren C1
and so on . I am using tree view library which requires only this structure
var tree=[
{
'Name': 'A',
'children': [
{
Name: '',
children: [
]
}
]
}
]
and so on. I want to convert my path structure to tree. Need help I can I achieve this with plain javasript.
Thanks
2 Answers 2
Just another approach with a helper object for keeping the reference to the named objects.
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; }
Comments
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
It creates the following structure:
[{
name:"A",
children:[
"Children A1",
{name:B", children:[...]}
]
}]
It simply iterates over all elements and resolves the path trough searching the right path object in an array, if a path element does not exist it creates it.
The upper code can be shortified to:
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),[]);