Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
var isArray = require('lodash.isarray');
var assign = require('lodash.assign');
var property = require('nested-property');
var keyBy = require('lodash.keyby');

var createTree = function(array, rootNodes, customID) {
var tree = [];
Expand All @@ -25,8 +26,13 @@ var createTree = function(array, rootNodes, customID) {
};

var groupByParents = function(array, options) {
var arrayByID = keyBy(array, options.customID);

return array.reduce(function(prev, item) {
var parentID = property.get(item, options.parentProperty) || options.rootID;
var parentID = property.get(item, options.parentProperty);
if (!parentID || !arrayByID.hasOwnProperty(parentID)) {
parentID = options.rootID;
}

if (parentID && prev.hasOwnProperty(parentID)) {
prev[parentID].push(item);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"dependencies": {
"lodash.assign": "^4.0.6",
"lodash.isarray": "^4.0.0",
"lodash.keyby": "^4.6.0",
"nested-property": "^0.0.7"
}
}
15 changes: 15 additions & 0 deletions test/fixtures/expected-orphan.fixture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = [{
id: 1,
parent_id: null,
children: [{
id: 2,
parent_id: 1,
children: [{
id: 3,
parent_id: 2
}]
}]
}, {
id: 4,
parent_id: 5
}];
13 changes: 13 additions & 0 deletions test/fixtures/initial-orphan.fixture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = [{
id: 1,
parent_id: null
}, {
id: 2,
parent_id: 1
}, {
id: 3,
parent_id: 2
}, {
id: 4,
parent_id: 5
}];
8 changes: 8 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ var customExpected = require('./fixtures/expected-custom.fixture.js');
var customInitial = require('./fixtures/initial-custom.fixture.js');
var nestedInitial = require('./fixtures/initial-nested.fixture.js');
var nestedExpected = require('./fixtures/expected-nested.fixture.js');
var orphanInitial = require('./fixtures/initial-orphan.fixture.js');
var orphanExpected = require('./fixtures/expected-orphan.fixture.js');

var current;

Expand Down Expand Up @@ -89,5 +91,11 @@ describe('array-to-tree', function() {
expect(current)
.to.be.deep.equal(nestedExpected);
});
it('should work with orphan nodes', function() {
current = toTree(orphanInitial);

expect(current)
.to.be.deep.equal(orphanExpected);
});
});
});