检索嵌套对象JavaScript

时间:2017-01-05 23:48:03

标签: javascript firebase firebase-realtime-database javascript-objects

我在console.log时的Firebase中的对象:

Object {AW: Object, Qdoba: Object}

然后在AW和Qdoba的餐厅标题下,我有标题和地址,我可以在我的控制台中展开和查看。我想在我的网页上显示两家餐馆的所有数据。

如何在不知道AWQdoba的情况下访问这两个餐厅对象?我的代码如下。

// Initialize Firebase
var config = {
  apiKey: "xxxxxxxx",
  authDomain: "xxxxxxxx",
  databaseURL: "xxxxxxxx",
  storageBucket: "xxxxx.xxxxxx.com",
  messagingSenderId: "xxxxx"
};

firebase.initializeApp(config);

var firebaseRef = firebase.database().ref('listings/');

//load 
firebaseRef.on("value", function(snapshot) {
  document
    .querySelector('#contacts')
    .innerHTML += contactHtmlFromObject(snapshot.val());
});

//prepare object's HTML
function contactHtmlFromObject(item){
  console.log(item)
  var html = '';
  html += '<li class="list-group-item contact">';
    html += '<div>';
      html += '<p class="lead">'+item.title+'</p>';
      html += '<p>'+item.title+'</p>';
      html += '<p><small title="'
                +item.title+'">'
                +item.address
                +'</small></p>';
    html += '</div>';
  html += '</li>';
  return html;
}

我的Firebase设置:

 {
  "listings" : {
    "A&W" : {
      "active" : true,
      "address" : "3939",
      "description" : "Super good root beer",
      "title" : "A&W"
    },
    "Qdoba" : {
      "active" : true,
      "address" : "1234 main",
      "description" : "A really good place to eat",
      "title" : "Gellas"
    }
  }
}

2 个答案:

答案 0 :(得分:1)

传递Snapshot本身并使用其forEach方法枚举项目:

firebaseRef.on("value", function(snapshot) {
  document
    .querySelector('#contacts')
    .innerHTML += contactHtmlFromObject(snapshot);
});

function contactHtmlFromObject(snapshot) {
  var html = '';
  snapshot.forEach(function (itemSnapshot) {
    var key = itemSnapshot.key; // This is "A&W" or "Qdoba", etc.
    var val = itemSnapshot.val();
    html += '<li class="list-group-item contact">';
      html += '<div>';
        html += '<p class="lead">'+val.title+'</p>';
        html += '<p>'+val.title+'</p>';
        html += '<p><small title="'
                  +val.title+'">'
                  +val.address
                  +'</small></p>';
      html += '</div>';
    html += '</li>';
  });
  return html;
}

答案 1 :(得分:1)

修改您的JSON以创建餐馆数组,并将每个名称作为属性。然后,您无需知道企业名称即可访问数据。

 {
  "listings" : [
    {          
      "name" : "A&W",
      "active" : true,
      "address" : "3939",
      "description" : "Super good root beer",
      "title" : "A&W"
    },
    {
      "name" : "Qdoba",
      "active" : true,
      "address" : "1234 main",
      "description" : "A really good place to eat",
      "title" : "Gellas"
    }
  ]
}

但是如果你不能这样做,例如post-SQL数据库可能不会给你回发,那么使用JQuery-function $ .each的一小段脚本可以遍历对象并输出一些数组将键作为属性的对象。

&#13;
&#13;
// this simulates the data being called in via ajax etc.
var data=JSON.parse(' {  "listings" : {    "A&W" : {      "active" : true,      "address" : "3939",      "description" : "Super good root beer",      "title" : "A&W"    },    "Qdoba" : {      "active" : true,      "address" : "1234 main",      "description" : "A really good place to eat",      "title" : "Gellas"    }  }}')

// make a new array to receive the objects
var arr = []
$.each(data.listings, function (key, data) {
    data.name = key // put the object key inside the object as paramater 'name'
    arr.push(data) // put the object into the array
})

// At this point we have an array of objects to do with as we wish.

// Output in readable form.
$("#jsonout").html(JSON.stringify(arr, undefined, 2))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="jsonout"></pre>
&#13;
&#13;
&#13;

有用的研究:文章here证明Firebase不返回数组的原因。