Skip to content

Instantly share code, notes, and snippets.

@mathiasschopmans
Created January 2, 2023 12:49
Show Gist options
  • Save mathiasschopmans/21e7c95592ec7e49cc60339d66429a1c to your computer and use it in GitHub Desktop.
Save mathiasschopmans/21e7c95592ec7e49cc60339d66429a1c to your computer and use it in GitHub Desktop.
pluck recursive attribute with native methods
export function pluckRecursive(input: any, prop: string, collect = []) {
collect = collect || [];
if (!input) return collect;
if (Array.isArray(input)) {
input.forEach(function (value) {
pluckRecursive(value, prop, collect);
})
} else if (typeof input === 'object') {
for (const [key, value] of Object.entries(input)) {
if (key === prop) {
collect.push(value);
} else {
pluckRecursive(value, prop, collect);
}
}
}
return collect;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment