Skip to content

Instantly share code, notes, and snippets.

@smrchy
Last active December 25, 2015 21:09
Show Gist options
  • Select an option

  • Save smrchy/7040781 to your computer and use it in GitHub Desktop.

Select an option

Save smrchy/7040781 to your computer and use it in GitHub Desktop.
Transform a correctly sorted SQL query with id and parentid into a tree object. Use `_queryTreeSort()` to sort you SQL query.

_makeTree

Transform a correctly sorted SQL query with id and parentid into a tree object. Use _queryTreeSort() to sort you SQL query.

Parameters:

  • q (Array): A query result (see example below)
  • id (String): The name of the id column (Default: "id")
  • parentid (String): The name of the ParentItemID column (Default: "parentid")
  • children (String): The name of the "children" array to be created in rows that have children (Default: "children")

Example:

_makeTree({ q:
	[
		{"id": 123, "parentid": 0, "name": "Mammals"},
		{"id": 456, "parentid": 123, "name": "Dogs"},
		{"id": 214, "parentid": 456, "name": "Labradors"},
		{"id": 810, "parentid": 456, "name": "Pugs"},
		{"id": 919, "parentid": 456, "name": "Terriers"}
	]
});

Result:

[
	{
		"id": 123,
		"parentid": 0,
		"name": "Mammals",
		"children": [
			{
				"id": 456,
				"parentid": 123,
				"name": "Dogs",
				"children": [
					{
						"id": 214,
						"parentid": 456,
						"name": "Labradors"
					},
					{
						"id": 810,
						"parentid": 456,
						"name": "Pugs"
					},
					{
						"id": 919,
						"parentid": 456,
						"name": "Terriers"
					}
				]
			}
		]
	}
]

What now?

Use the result to display your tree with a recursive function like _renderTree()

_makeTree = (options) ->
id = options.id or "id"
pid = options.parentid or "parentid"
children = options.children or "children"
temp = {}
o = []
# Create the tree
for e in options.q
# Add the row to the index
temp[e[id]] = e
# This parent should be in the index
if temp[e[pid]]?
# This row is a child
# Does its parent have children alrdy?
if not temp[e[pid]][children]?
temp[e[pid]][children] = []
# Add the child to the parent
temp[e[pid]][children].push(e)
else
# Add a root item
o.push(e)
return o
var _makeTree = function(options) {
var children, e, id, o, pid, temp, _i, _len, _ref;
id = options.id || "id";
pid = options.parentid || "parentid";
children = options.children || "children";
temp = {};
o = [];
_ref = options.q;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
temp[e[id]] = e;
if (temp[e[pid]] != null) {
if (temp[e[pid]][children] == null) {
temp[e[pid]][children] = [];
}
temp[e[pid]][children].push(e);
} else {
o.push(e);
}
}
return o;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment