0

我有嵌套对象,它包含随机数据类型,如字符串、数字、数组等。

例如,

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

如何从上面的示例中获取所有密钥,如下所示,

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

对象结构应更改为任何嵌套类型。

谢谢提前!!!

4

2 回答 2

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' ]
于 2021-04-29T17:38:03.010 回答
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);
}

你所有的钥匙都这样

于 2021-04-29T18:39:16.313 回答