Created
December 18, 2021 02:37
-
-
Save shawn-dsz/a778c901be9cf6e5503a745bd9dda0bd to your computer and use it in GitHub Desktop.
get id recursively
This file contains hidden or 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 myObj = { | |
| id: 1, | |
| anyProp: [{ | |
| id: 2, | |
| thing: { a: 1, id: 10 }, | |
| children: [{ id: 3 }] | |
| }, { | |
| id: 4, | |
| children: [{ | |
| id: 5, | |
| children: [{ | |
| id: 6, | |
| children: [{ id: 7 }] | |
| }] | |
| }] | |
| }] | |
| }; | |
| const getValues = prop => obj => { | |
| if (!Object.keys(obj).length) { return []; } | |
| return Object.entries(obj).reduce((acc, [key, val]) => { | |
| if (key === prop) { | |
| acc.push(val); | |
| } else { | |
| acc.push(Array.isArray(val) ? val.map(getIds).flat() : getIds(val)); | |
| } | |
| return acc.flat(); | |
| }, []); | |
| } | |
| const getIds = getValues('id'); | |
| console.log(getIds(myObj)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment