_.tree is an extension for underscore.js, which converts flat Collections into tree structures.
Take the following collection. Each item in the collection has an id and a parent_id, describing how it relates to other items.
var input = [
{ id: 1, name: 'Grandfather', parent_id: 0 },
{ id: 2, name: 'Father', parent_id: 1 },
{ id: 3, name: 'Son', parent_id: 2 },
{ id: 4, name: 'Daughter', parent_id: 2 }
];
By running _.tree(input)
, we would get something like the following:
{
"id": 1,
"name": "Grandfather",
"parent_id": 0,
"groups": [
{
"id": 2,
"name": "Father",
"parent_id": 1,
"groups": [
{
"id": 3,
"name": "Son",
"parent_id": 2,
"groups": []
},
{
"id": 4,
"name": "Daughter",
"parent_id": 2,
"groups": []
}
]
}
]
}
- data is the input data. This is the only required parameter.
- rootId is the value of the root item's primary key. Defaults to the first ID found, or
0
. - pkName is the name of the primary key attribute. Defaults to
id
. - fkName is the name of the foreign key attribute. Defaults to
parent_id
.