Created
January 2, 2023 12:49
-
-
Save mathiasschopmans/21e7c95592ec7e49cc60339d66429a1c to your computer and use it in GitHub Desktop.
pluck recursive attribute with native methods
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
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