console.log 时来自 Firebase 的对象:
Object {AW: Object, Qdoba: Object}
然后,在 AW 和 Qdoba 的餐厅标题下,我有标题和地址,我可以展开并在控制台中查看它们。我想在我的网页中显示两家餐厅的所有数据。
在不知道 AW
和 Qdoba
的情况下,如何访问两个餐厅对象?我的代码如下。
// 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"
}
}
}
最佳答案
通过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;
}
关于javascript - 检索嵌套对象 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41496705/