Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, we will see how can we get all keys from JSON objects, here we will use a custom function which will return the list of keys available in a JSON object.

So, we will create a function that navigates every possible object’s key and add keys in an array that returns at the end of recursive loops.

Well, let’s create a function that returns the keys of nested objects.

const getNestedKeys = (data, keys) => {
  if(!(data instanceof Array) && typeof data == 'object'){
    Object.keys(data).forEach(key => {
      keys.push(key);
      const value = data[key];
      if(typeof value === 'object' && !(value instanceof Array)){
         getNestedKeys(value, keys);
      }
   });
  }
  return keys
}

In javascript when we check typeof of the array it will return i.e we use instanceof Array to handle array types of object.

Let’s take an example below the nested object.

const data = {
  person: {
    male: {
      name: "infinitbility"
    },
    female: {
      name: "aguidehub"
    }
  }
};

const getNestedKeys = (data, keys) => {
  if(!(data instanceof Array) && typeof data == 'object'){
    Object.keys(data).forEach(key => {
      keys.push(key);
      const value = data[key];
      if(typeof value === 'object' && !(value instanceof Array)){
         getNestedKeys(value, keys);
      }
   });
  }
  return keys
}

getNestedKeys(data, []);
// [ 'person', 'male', 'name', 'female', 'name' ]

When you run above code, you will get [ 'person', 'male', 'name', 'female', 'name' ] let’s check the output.

JavaScript, Get all keys from nested json object example
JavaScript, Get all keys from nested json object example

Want to reomove duplicate, read below tutorial.

https://infinitbility.com/how-to-remove-duplicates-from-array-of-strings-in-javascript

All the best đź‘Ť.