如何循环我从 firebase api 获得的这个 json 对象,以获得“Rachel Howell”?

时间:2021-06-13 15:49:38

标签: javascript json firebase loops object

我试过了:

Object.keys(user).forEach(item => {
  console.log(item)
})

但响应只是 5

{
  "5": {
    "avatar": "https://reqres.in/img/faces/12-image.jpg",
    "banner": "https://via.placeholder.com/1500x500.png?text= Banner",
    "email": "rachel.howell@reqres.in",
    "id": 12,
    "links": {
      "fb": "https://www.facebook.com/",
      "ig": "https://www.facebook.com/",
      "twt": "https://www.facebook.com/",
      "yt": "https://www.facebook.com/"
    },
    "name": "Rachel Howell",
    "walletAddress": "howell111"

  }
}

1 个答案:

答案 0 :(得分:0)

因此,如果您知道它将向下一层,那么您可以通过以下方式列出向下一层的所有内容:

Object.keys(user).forEach(item => {
  Object.keys(user[item]).forEach(innerItem =>{
    console.log(innerItem + ': ' + user[item][innerItem])

} ) })

如果你知道你想要名字,那么你可以修改上面的内容

if (innerItem == 'name'){ //or ===
  console.log(innerItem + ': ' + user[item][innerItem])}

或者如evolutionxbox所评论的:

Object.keys(user).forEach(item => {

  console.log(user[item].name)}

)

另一方面,如果你想要所有简单的属性,但你不知道它们有多深,你可以做以下改编自traversing through JSON string to inner levels using recursive function

function scan(obj, propName) {
var k;
if (obj instanceof Object) {
    for (k in obj){
        if (obj.hasOwnProperty(k)){
            //recursive call to scan property
            scan( obj[k], k );  
        }                
    }
} else {
    //obj is not an instance of Object so obj here is a value
    console.log(propName+': '+ obj)
};

};

扫描(用户,'顶部')

如果您知道只需要名称,请按如下方式阻止控制台日志:

if (propName === 'name'){
    console.log(propName+': '+ obj)}