Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.