Let's assume that you have the following object:
javascriptlet obj = { 'name': 'Erik', 'age': 30, 'location': { 'city': 'Barcelona' }, 'measures':{ 'body':{ 'height': 177, 'weight': 72 } } }
It has the following keys:
name
age
location.city
measures.body.height
measures.body.weight
You can use recursion to get all the nested keys and subkeys:
jsxconst getDeepKeys = (obj) => { let keys = Object.keys(obj).map(key => { if(typeof obj[key] === 'object'){ let subkeys = getDeepKeys(obj[key]); return subkeys.map(subkey => key + '.' + subkey); } else{ return key; } }); return keys.flat(Infinity); }
Result:
javascriptconsole.log(getDeepKeys(obj)); // ["name", "age", "location.city", "measures.body.height", "measures.body.weight"]
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.