-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree-plugin-underscore.js
More file actions
25 lines (18 loc) · 932 Bytes
/
tree-plugin-underscore.js
File metadata and controls
25 lines (18 loc) · 932 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(function() {
var matchAttribute = function (key, value, dataObject) {
return (value.toString() === (_.property(key)(dataObject) || "").toString());
};
var buildTree = function(flatArray, rootIdValue, idName, parentIdName, childrenCollectionName) {
idName = idName || 'id';
parentIdName = parentIdName || 'parentId';
childrenCollectionName = childrenCollectionName || 'children';
rootIdValue = rootIdValue || (_.first(flatArray))[idName] || 0;
var output = JSON.parse(JSON.stringify(_.find(flatArray, _.partial(matchAttribute, idName, rootIdValue))));
var children = _.filter(flatArray, _.partial(matchAttribute, parentIdName, rootIdValue));
output[childrenCollectionName] = _.map(children, function(child) {
return buildTree (flatArray, child[idName], idName, parentIdName, childrenCollectionName);
});
return output;
};
_.mixin ({tree: buildTree});
}).call(this);