Created
February 14, 2016 03:17
-
-
Save badri/9568d147c30ba3a14a6b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION get_tree(data json) RETURNS json AS $$ | |
var root = []; | |
for(var i in data) { | |
build_tree(data[i]['id'], data[i]['name'], data[i]['children']); | |
} | |
function build_tree(id, name, children) { | |
var exists = getObject(root, id); | |
if(exists) { | |
exists['children'] = children; | |
} | |
else { | |
root.push({'id': id, 'name': name, 'children': children}); | |
} | |
} | |
function getObject(theObject, id) { | |
var result = null; | |
if(theObject instanceof Array) { | |
for(var i = 0; i < theObject.length; i++) { | |
result = getObject(theObject[i], id); | |
if (result) { | |
break; | |
} | |
} | |
} | |
else | |
{ | |
for(var prop in theObject) { | |
if(prop == 'id') { | |
if(theObject[prop] === id) { | |
return theObject; | |
} | |
} | |
if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) { | |
result = getObject(theObject[prop], id); | |
if (result) { | |
break; | |
} | |
} | |
} | |
} | |
return result; | |
} | |
return JSON.stringify(root); | |
$$ LANGUAGE plv8 IMMUTABLE STRICT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment