Change Utils.unflatten to accept an object as second argument; make name of children property customizable

This commit is contained in:
SachaG 2017-05-06 16:12:44 +09:00
parent 6cff2b19fd
commit 3b651a6d2b
3 changed files with 11 additions and 5 deletions

View file

@ -26,7 +26,7 @@ class CategoriesList extends Component {
};
});
const nestedCategories = Utils.unflatten(categoriesClone, '_id', 'parentId');
const nestedCategories = Utils.unflatten(categoriesClone, {idProperty: '_id', parentIdProperty: 'parentId'});
return nestedCategories;
}

View file

@ -14,7 +14,7 @@ const PostsCommentsThread = (props, context) => {
} else {
const resultsClone = _.map(results, _.clone); // we don't want to modify the objects we got from props
const nestedComments = Utils.unflatten(resultsClone, '_id', 'parentCommentId');
const nestedComments = Utils.unflatten(resultsClone, {idProperty: '_id', parentIdProperty: 'parentCommentId'});
return (
<div className="posts-comments-thread">

View file

@ -308,7 +308,13 @@ Utils.findIndex = (array, predicate) => {
}
// adapted from http://stackoverflow.com/a/22072374/649299
Utils.unflatten = function(array, idProperty, parentIdProperty, parent, level=0, tree){
Utils.unflatten = function(array, options, parent, level=0, tree){
const {
idProperty = '_id',
parentIdProperty = 'parentId',
childrenProperty = 'childrenResults'
} = options;
level++;
@ -334,13 +340,13 @@ Utils.unflatten = function(array, idProperty, parentIdProperty, parent, level=0,
tree = children;
} else {
// else, we add the children to the parent as the "childrenResults" property
parent.childrenResults = children;
parent[childrenProperty] = children;
}
// we call the function on each child
children.forEach(child => {
child.level = level;
Utils.unflatten(array, idProperty, parentIdProperty, child, level);
Utils.unflatten(array, options, child, level);
});
}