Get all the keys from an object

Let's assume that you have the following object:

javascript
let 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:

jsx
const 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:

javascript
console.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.