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.
1const getNestedKeys = (data, keys) => {2 if(!(data instanceof Array) && typeof data == 'object'){3 Object.keys(data).forEach(key => {4 keys.push(key);5 const value = data[key];6 if(typeof value === 'object' && !(value instanceof Array)){7 getNestedKeys(value, keys);8 }9 });10 }11 return keys12}
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.
1const data = {2 person: {3 male: {4 name: "infinitbility"5 },6 female: {7 name: "aguidehub"8 }9 }10};1112const getNestedKeys = (data, keys) => {13 if(!(data instanceof Array) && typeof data == 'object'){14 Object.keys(data).forEach(key => {15 keys.push(key);16 const value = data[key];17 if(typeof value === 'object' && !(value instanceof Array)){18 getNestedKeys(value, keys);19 }20 });21 }22 return keys23}2425getNestedKeys(data, []);26// [ 'person', 'male', 'name', 'female', 'name' ]
When you run above code, you will get [ 'person', 'male', 'name', 'female', 'name' ]
let’s check the output.

Want to reomove duplicate, read below tutorial.
https://infinitbility.com/how-to-remove-duplicates-from-array-of-strings-in-javascript
All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.