有没有办法让我检索值的名称? 例如:
我想用黄色突出显示值名称。
但是,现在我只能得到:
据我了解,以下代码仅返回玩家得分的值。
var childData = childSnapshot.val();
我可以做这样的事情来获取值名称吗?
var childValueName = childSnapshot.val().name;
这是我的Java代码:
function PrintData()
{
var ref = firebase.database().ref('Score');
var PrintData = document.getElementById('PrintOutData');
ref.on("value", function(snapshot)
{
PrintData.innerText = "";
snapshot.forEach(function(childSnapshot)
{
console.log("childSnapshot.key: " + childSnapshot.key);
var childData = childSnapshot.val();
let keys = Object.keys(childData)
keys.forEach(key => {
let value = childData[key.toString()];
console.log("value: " + value);
PrintData.innerText += childSnapshot.key + ": " + value +"\r";
})
});
});
}
我的html代码:
<button type="button" onclick="PrintData()">Print!</button>
如果我错了,请纠正我!谢谢。
答案 0 :(得分:0)
Firebase有一个精通而精美的文档。 根据{{3}},当您将相对路径传递给child()方法时,将返回datasnapshot
// Assume we have the following data in the Database:
{
"name": {
"first": "Ada",
"last": "Lovelace"
}
}
// Test for the existence of certain keys within a DataSnapshot
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var name = snapshot.child("name").val(); // {first:"Ada",last:"Lovelace"}
var firstName = snapshot.child("name/first").val(); // "Ada"
var lastName = snapshot.child("name").child("last").val(); // "Lovelace"
var age = snapshot.child("age").val(); // null
});
答案 1 :(得分:0)
以下内容可能对您有用:
firebase.database().ref('score').once('value', snap => {
var data = snap.val() // should return => {User1: {GamePlay00: 3}, User2:
{GamePlay00: 1}, ...}
var users = Object.keys('data') should return // => [User1, User2, ...]
var usersDatas = users.map(user_id => data[user_id]) // should return something like => [{gamePlay00: 3}, {gamePlay00:1}, ...]
var value = usersDatas.map(game_play_id => game_play_id) // should return => [gamePlay00, gamePlay00...]
})
请参阅以下链接以获取更多文档:Object.keys Firebase Docs
答案 2 :(得分:0)
我也坚持将Snapshot.forEach()
用于较低级别:
var ref = firebase.database().ref('Score');
var PrintData = document.getElementById('PrintOutData');
ref.on("value", function(snapshot) {
PrintData.innerText = "";
snapshot.forEach(function(userSnapshot) {
console.log("childSnapshot.key: " + userSnapshot.key);
userSnapshot.forEach(function(gameSnapshot) {
PrintData.innerText += gameSnapshot.key + ": " + gameSnapshot.val() +"\r";
})
});
});
答案 3 :(得分:0)
请参见firebase.database.DataSnapshot
键 (字符串或空值)
此DataSnapshot位置的键(路径的最后一部分)。
数据库位置中的最后一个令牌被视为其密钥。例如,“ ada”是/ users / ada /节点的键。访问任何DataSnapshot
上的密钥将返回生成密钥的位置的密钥。但是,访问数据库根URL上的密钥将返回null
。
// Assume we have the following data in the Database:
{
"name": {
"first": "Ada",
"last": "Lovelace"
}
}
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "ada"
var childKey = snapshot.child("name/last").key; // "last"
});