-1

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') );
 }
Subhash
  • 363
  • 1
  • 4
  • 15

1 Answers1

0

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
}
alpham8
  • 1,314
  • 2
  • 14
  • 32
  • I dont know the depth of the tree. so i cannot use the object notation @alpham8 – Subhash Nov 18 '16 at 11:00
  • But you can iterate over it. That was just a simple example. You can recursive iterate over it. Inform yourself about function recursively loop: http://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively – alpham8 Nov 18 '16 at 11:31