Last active
March 23, 2019 03:07
-
-
Save unyo/139aa6823d4008bd276c5ed643f0d64b to your computer and use it in GitHub Desktop.
get all object keys js
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 getObjectKeys = (obj, prefix = '') => { | |
return Object.entries(obj).reduce((collector, [key, val]) => { | |
const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ] | |
if (Object.prototype.toString.call(val) === '[object Object]') { | |
const newPrefix = prefix ? `${prefix}.${key}` : key | |
const otherKeys = getObjectKeys(val, newPrefix) | |
return [ ...newKeys, ...otherKeys ] | |
} | |
return newKeys | |
}, []) | |
} | |
/* | |
getObjectKeys({x: 1, y: 2, z: {a: 1, b: 2, c: { d: 1, e: 2 }}}) | |
> ["x", "y", "z", "z.a", "z.b", "z.c", "z.c.d", "z.c.e"] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment