Skip to content

Instantly share code, notes, and snippets.

@iamandrewluca
Last active October 1, 2019 06:37
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 iamandrewluca/bd0564ea735b406711e8c1e73e1717a1 to your computer and use it in GitHub Desktop.
Save iamandrewluca/bd0564ea735b406711e8c1e73e1717a1 to your computer and use it in GitHub Desktop.
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