Subhash Subhash - 20 days ago 7
AngularJS Question

Conversion of JSON into tree like JSON

I need to convert treeData JSON into a different for so i can use some visualization library in java script on it.

treeData={
"leftNode": {
"leftNode": {
"leftNode": {
"leftNode": {
"leftNode": "fence_brand_name = 'reebok'",
"rightNode": "fence_brand_id = 123",
"centerOperator": "OR"
},
"rightNode": "fence_category_name = 'shoes'",
"centerOperator": "AND"
},
"rightNode": "latitude > 19.1140997",
"centerOperator": "AND"
},
"rightNode": "latitude = 72.89498",
"centerOperator": "AND"
},
"rightNode": "radius = 5000",
"centerOperator": "AND"
}


The depth of this tree can be anything and the form I want to convert this into is

newTreeData=[{
leftNode=[{
leftNode=[{
leftNode="left"
rightNode="right",
centerOperator="op"
}],
rightNode="right",
centerOperator="op"
}],
rightNode="right",
centerOperator="op"
}]


I'm tried using this code but no results so far.

var addNodes=function(data){
if(isObj(data.leftNode)){
var right=data.rightNode;
var center=data.centerOperator;
newTreeData.push(rightNode:right,newCenterOperator:center,leftNode:[]);
addNodes(data.leftNode);
}else{
newTreeData.push(rightNode:data.rightNode,centerOperator:data.centerOperator,leftNode:[]);
}
}

var function isObj(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}

Answer

You don't need that, because you can access JSON object also in the Array notation, like this:

treeData["leftNode"]["leftNode"]

or with object notation like this:

treeData.leftNode.leftNode

Of course you can also iterate over it, e. g.:

for (var leftNode in treeData.leftNode) {
    // do something with leftNode
}