Skip to content

Instantly share code, notes, and snippets.

@unyo
Last active March 23, 2019 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unyo/139aa6823d4008bd276c5ed643f0d64b to your computer and use it in GitHub Desktop.
Save unyo/139aa6823d4008bd276c5ed643f0d64b to your computer and use it in GitHub Desktop.
get all object keys js
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