JSFiddle - React, Tailwind, and code Playground
by nrabinowitz
HTML
<pre></pre>
JavaScript
var input = [
{"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
}
];
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;
}
}
$('pre').html(JSON.stringify(convert(input, "root"), null, ' '));