var formatCollection function function findNode id data for var index

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var formatCollection = (function () {
function findNode(id, data) {
for (var index = 0; index < data.length; index++) {
if (data[index].id == id) {
return data[index].children;
} else {
var children = data[index].children;
var node = findNode(id, children);
if (node) {
return node;
}
}
}
}
function makeList(nodes, results) {
nodes = _.sortBy(nodes, function (node) {
return node['item'].position;
});
_.forEach(nodes, function (node) {
results.push(node.item);
makeList(node.children, results);
});
}
return function (collection) {
var data = [
{
id: 0,
children: []
}
];
while (collection.length > 0) {
var item = collection.shift();
var node = findNode(item.parentId || 0, data);
if (node) {
node.push({
id: item.id,
item: item,
children: []
});
} else {
collection.push(item);
}
}
var formattedCollection = [];
makeList(data[0].children, formattedCollection, 0);
return formattedCollection;
};
})();