Skip to content

Instantly share code, notes, and snippets.

@shawn-dsz
Created December 18, 2021 02:37
Show Gist options
  • Save shawn-dsz/a778c901be9cf6e5503a745bd9dda0bd to your computer and use it in GitHub Desktop.
Save shawn-dsz/a778c901be9cf6e5503a745bd9dda0bd to your computer and use it in GitHub Desktop.
get id recursively
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