Last active
October 1, 2019 06:37
-
-
Save iamandrewluca/bd0564ea735b406711e8c1e73e1717a1 to your computer and use it in GitHub Desktop.
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 theObject = { | |
nested1: { | |
key1: "value1", | |
nested2: { | |
key2: "value2" | |
} | |
}, | |
key3: "value3", | |
key4: ["test", "test1"] | |
}; | |
function flatKeys(obj, prefix = "") { | |
return Object.keys(obj).reduce(function (res, el) { | |
// uncomment this block if don't want array indexes | |
// if (Array.isArray(obj[el])) { | |
// return [...res, el]; | |
// } | |
if (typeof obj[el] === "object" && obj[el] !== null) { | |
return [...res, ...flatKeys(obj[el], prefix + el + ".")]; | |
} | |
return [...res, prefix + el]; | |
}, []); | |
} | |
const objectKeys = flatKeys(theObject) | |
console.log(JSON.stringify(objectKeys, null, 2)) | |
/** | |
* [ | |
* "nested1.key1", | |
* "nested1.nested2.key2", | |
* "key3", | |
* "key4.0", | |
* "key4.1" | |
* ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment