Skip to content

Instantly share code, notes, and snippets.

@kalinchernev
Last active September 2, 2020 19:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalinchernev/1db8f0a2176ddf55f9c08894a413a927 to your computer and use it in GitHub Desktop.
Save kalinchernev/1db8f0a2176ddf55f9c08894a413a927 to your computer and use it in GitHub Desktop.
nest objects by 2 props: id and parent
const nest = (items, parent = 0) => {
const nested = [];
Object.values(items).forEach(item => {
// parent can be a string or a number
/* eslint-disable-next-line eqeqeq */
if (item.parent == parent) {
const children = nest(items, item.id);
if (children.length) {
/* eslint-disable-next-line no-param-reassign */
item.children = children;
}
nested.push(item);
}
});
return nested;
};
export default nest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment