I tried to format a array to object. it's working fine but I need to know, Is this correct or wrong? any other standard way to do this?.
I used underscoreJS for this.
//What I get from API
"A/a/1" = A -> Category, a -> Subcategory, 1 -> child of subcategory.
["A", "A/a", "A/b", "A/a/1", "A/a/2", "B", "B/a"];
//Which format i need.
[
{
"name":"A",
"parent":"",
"children":[
{
"name":"a",
"parent":"A",
"children":[
{
"name":"1",
"parent":"a",
"children":[
]
},
{
"name":"2",
"parent":"a",
"children":[
]
}
]
},
{
"name":"b",
"parent":"A",
"children":[
]
}
]
},
{
"name":"B",
"parent":"",
"children":[
{
"name":"a",
"parent":"B",
"children":[
]
}
]
}
]
MY CODE :
var dataObj = function(){
this.name = "";
this.parent = "";
this.administrator = "";
this.children = [];
};
var d_ = [];
_.each(data, function(item, index){
var row = new dataObj();
var item_array = item.split("/"),
item_array_length = item_array.length;
if(item_array.length == 1){
row.name = item_array[0];
d_.push(row);
} else {
row.name = item_array[1];
row.parent = item_array[0];
var newC = d_[_.findIndex(d_, {name:item_array[0]})];
if(item_array.length == 2) {
newC.children.push(row);
} else if(item_array.length == 3) {
newC.children[_.findIndex(newC.children, {name: item_array[1]})]
.children.push({name : item_array[2], parent : item_array[1]});
}
}
});
UPDATE The level of subcategory is not limited. "A/a/1/i/n/x/y...."