Create a nested array recursively in CoffeeScript
In an old post called Create a nested array recursively in Javascript I wrote how to go from
[
{id: 1, title: 'hello', parent: 0},
{id: 2, title: 'hello', parent: 0},
{id: 3, title: 'hello', parent: 1},
{id: 4, title: 'hello', parent: 3},
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4},
{id: 7, title: 'hello', parent: 3},
{id: 8, title: 'hello', parent: 2}
]
to
[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
]
with a recursive Javascript function.
I’ve been asked to show how to do this in Coffeescript.
getNestedChildren = (arr, parent) ->
out = []
for item in arr
continue unless item.parent is parent
children = getNestedChildren arr, item.id
item.children = children if children.length
out.push item
out
which compiles to this Javascript:
var getNestedChildren;
getNestedChildren = function(arr, parent) {
var children, item, out, _i, _len;
out = [];
for (_i = 0, _len = arr.length; _i < _len; _i++) {
item = arr[_i];
if (item.parent !== parent) {
continue;
}
children = getNestedChildren(arr, item.id);
if (children.length) {
item.children = children;
}
out.push(item);
}
return out;
};
On js2coffee you can convert Javascript to and form Coffeescript.