0

I have nested object it contains random data types like string, number , array , etc.

for example,

const exampleObj = {
name : "william",
age : 23,
habbits : ["studying","running"],
authInfo : {
email : "william@gmail.com",
password : "foo@123"
}
}

how to get all the keys from above example like this,

["name","age","habbits","authInfo.email","authInfo.pasword"]

The object structure should be change to any nested type.

Thanks adavance !!!

Robin Rogh
  • 11
  • 1

2 Answers2

0
function getAllKeys(){
  const exampleObj   = {
    name : "william",
    age : 23,
    habbits : ["studying","running"],
    authInfo : {
    email : "william@gmail.com",
    password : "foo@123"
    }
  }

  const fn = exampleObj  => {
    const keys = [];
    Object.keys({...exampleObj }).forEach(key => {
      keys.push(key);
      if (typeof exampleObj [key] == 'object') {      
        if(!Array.isArray(exampleObj [key])) keys.push(...fn(exampleObj [key]))
      }
    })
    return keys
  }

  console.log(fn(exampleObj ))
}
//> Array   [ 'name', 'age', 'habbits', 'authInfo', 'email', 'password' ]
Sergey
  • 1,111
  • 5
  • 7
0
for( x = 0; x < exampleObj.length; x++) {
    div = document.createElement('div');
    p = document.createElement('p');
    p.innerText = exampleObj[x].name;
    div.appendChild(p);

    p = document.createElement('p');
    p.innerText = exampleObj[x].age;
    div.appendChild(p);
}

like this for all your keys

Salichen
  • 47
  • 5