Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Clusterfck array to JavaScript InfoVis Toolkit json hierarchical

Currently I am using the javascript library Clusterfck to perform a data grouping. This library generates an array in the following format:

[
  {"canonical":[20,120,102],
   "size":1
  },
  {"canonical":[250,255,253],
   "left":{
      "canonical":[250,255,253],
      "size":1
    },
   "right":{
      "canonical":[255,255,240],
      "size":1
    },
   "size":2
  },
  {"canonical":[100,54,300],
   "size":1
  }
]

But javascript libraries for data visualization how D3.js and Jit using JSON structures as shown below:

{
    "canonical":"Pai",
    "children":[
        {"canonical":[20,120,102],  "size":1},
        {
            "canonical":[250,255,253],
            "children": [
                {"canonical":[250,255,253], "size":1},
                {"canonical":[255,255,240], "size":1}               
            ],
            "size":2
        },
        {
            "canonical":[100,54,300],
            "size":1
        }
    ]
}

I would like to convert these structures, using JavaScript or PHP. Could anyone help me?

like image 424
gilvandev Avatar asked Jun 10 '26 10:06

gilvandev


1 Answers

If you just want to convert between these structures, this is pretty simple. See working fiddle: http://jsfiddle.net/nrabinowitz/vuk94/

function convert(input, rootName) {
    // top level
    if (Array.isArray(input)) {
        return {
            "canonical": rootName,
            "children": input.map(convert)
        };
    }
    // node
    else {
        ['left', 'right'].forEach(function(side) {
            if (input[side]) {
                input.children = input.children || [];
                input.children.push(convert(input[side]));
                delete input[side];
            }
        });
        return input;
    }
}

This uses a couple of ECMAScript 1.5 features (Array.isArray, forEach, and map), but if you're using d3 you're probably targeting browsers that support this anyway.

like image 59
nrabinowitz Avatar answered Jun 12 '26 00:06

nrabinowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!