Last active
September 2, 2020 19:58
-
-
Save kalinchernev/1db8f0a2176ddf55f9c08894a413a927 to your computer and use it in GitHub Desktop.
nest objects by 2 props: id and parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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