 <p>So your nodes have a <code>name:</code> property and a <code>children:</code> array property. </p> <p>Databases typically store trees in tables as</p> <pre><code>node-id, parent-id, value1, ..., valueN </code></pre> <p>(you can get certain advantages if you store depth-first visit order and depth-first return order; ask in comments if you need the details).</p> <p>If you make a single query and get this data into JSON, you will have something like (for your illustration),</p> <pre><code>[{id: "0", parent: "-1", name: "A2"}, {id: "1", parent: "0", name: "A3"}, {id: "2", parent: "1", name: "A31"}, {id: "3", parent: "2", name: "A311"}, {id: "4", parent: "2", name: "A312"}] </code></pre> <p>You can convert this into <code>{name: children:}</code> format with the following code:</p> <pre><code> // data is an array in the above format function toTree(data) { var childrenById = {}; // of the form id: [child-ids] var nodes = {}; // of the form id: {name: children: } var i, row; // first pass: build child arrays and initial node array for (i=0; i&lt;data.length; i++) { row = data[i]; nodes[row.id] = {name: row.name, children: []}; if (row.parent == -1) { // assume -1 is used to mark the root's "parent" root = row.id; } else if (childrenById[row.parent] === undefined) { childrenById[row.parent] = [row.id]; } else { childrenById[row.parent].push(row.id); } } // second pass: build tree, using the awesome power of recursion! function expand(id) { if (childrenById[id] !== undefined) { for (var i=0; i &lt; childrenById[id].length; i ++) { var childId = childrenById[id][i]; nodes[id].children.push(expand(childId)); } } return nodes[id]; } return expand(root); } </code></pre> <p>See <a href="http://jsfiddle.net/z6GPB/" rel="nofollow">http://jsfiddle.net/z6GPB/</a> for a working example.</p>