How to retrieve data from Object [Firebase unique key] - javascript

This is the data that i want to retrieve
How can I retrieve the data without knowing the unique ID?
var query = firebase.database().ref("/Venue").orderByKey();
query.on("value", function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
console.log(childData);
});
});

Use Object.values to help. it returns an array of values of properties of an object
Since .Data has exactly one property, you can easily get its value, it will be at index 0
var query = firebase.database().ref("/Venue").orderByKey();
query.on("value", function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
console.log(Object.values(childData.Data)[0]); // change
});
});

Use Object.values:
var obj = {
Venue: {
Block_A: {
Data: {
Date: "19/03/2019",
Humi: 30,
Temp: 50,
Time: "12:56"
}
}
}
};
console.log(Object.values(obj.Venue.Block_A.Data));

Related

Sum object values

I'm trying to sum the values from the key "value" in the object data.
Googled alot but cant figure this out.
My guess is that i'm not retrieving the values from localStorage.
EDIT: And i want to save the summed values to localStorage...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name, bill.value, bill.id, bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill, billVal, id, false);
data.push({
name: bill,
value: billVal,
id: id,
payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t, { value }) => t + value, 0); // ?????
localStorage.setItem("Bills", JSON.stringify(data));
};
function newItem(name, value, id, payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id", id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
i'v tried to add .values before reduce but nothing works:
billsTotals.innerHTML = Object.values(data.value).reduce((t, {value}) => t + value, 0); // ?????
Not sure about your data variable. But the data variable is an array then you could do something like this.
data.reduce((total,{value})=>{
return total +value
},0)

How to get the value of an array inside an array?

I have to take each data of the array inside an array but it doesn't work when I use something like tmp.name or tmp[0].name would result undefined and even tmp.length result 0
var tmp = [];
var db = firebase.firestore();
var docCollection = db.collection('doctors');
var assignedDoctors = docCollection.where('assign', '==', user.key).get();
assignedDoctors.then(function(doc){
let i = 0;
doc.forEach(function(md){
tmp.push(md.data());
tmp[i].key = md.id;
i++;
});
}).catch(function(e){
console.log(e);
});
console.log(tmp)
the tmp result
[]
0: {assign: "userA", name: "NameA"}
1: {assign: "userA", name: "NameB"}
length: 2
__proto_: Array(0)
Just declare map and assign all data of md.data() to map and then push map into array and remove variable i as no need of it. Like following:
doc.forEach(function(md){
var map = {};
map = md.data();
map.key = md.id;
tmp.push(map);
});
var tmp = [];
var db = firebase.firestore();
var docCollection = db.collection('doctors');
var assignedDoctors = docCollection.where('assign', '==', user.key).get();
assignedDoctors.then(function(doc){
let i = 0;
doc.forEach(function(md){
tmp.push(md.data());
// tmp[i].key = md.id;
// i++;
});
}).catch(function(e){
console.log(e);
});
console.log(tmp)
comment these line and check it.

Firebase Web - Is it possible to get the value's name?

is there a way for me to retrieve the name of a value?
For example:
I want to get the value names highlighted in yellow.
However, right now I can only get:
From my understanding the below code only return the value which is the player's scores.
var childData = childSnapshot.val();
Can I do something like this to get the value name?
var childValueName = childSnapshot.val().name;
This is my java code:
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";
})
});
});
}
My html code:
<button type="button" onclick="PrintData()">Print!</button>
Please correct me if I am wrong! Thankyou.
See firebase.database.DataSnapshot
key
(string or null)
The key (last part of the path) of the location of this DataSnapshot.
The last token in a Database location is considered its key. For example, "ada" is the key for the /users/ada/ node. Accessing the key on any DataSnapshot will return the key for the location that generated it. However, accessing the key on the root URL of a Database will return 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"
});
Firebase has a well versed and beautiful documentation.
According to firebase documentation, datasnapshot is returned when you pass a relative path to the child() method
// 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
});
The following may work for your purpose:
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...]
})
Please refer to these link for further documentation: Object.keys Firebase Docs
I'd stick to using Snapshot.forEach() for the lower level too:
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";
})
});
});

Incrementing key value when save data to local storage

I want to save different objects with different key to local storage every time my button clicked. But always key == 0 and records doesn't create, one record in local storage only update,I think this is because key is always same. How I can change this,to put different objects to local storage?
(function() {
window.onload = function() {
var key = 0;
var storage = new Storage();
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
key++;
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
As localstorage API is implemented
You set an item for a keyName (1st argument):
localStorage.setItem(keyName, keyValue);
You get an item for a keyName:
var aValue = localStorage.getItem(keyName);
So in your case your Storage Object should be adapted since it seems like you need multiples keys but your get storage will only retrieve a fixed key='items'.
So, modify your Storage.get and pass a key when you call it:
function Storage() {
this._ITEMS_DESCRIPTOR = 'items'; // I guess a default key?
}
// let key be specified when method is called, or by default set it to the private property _ITEMS_DESCRIPTOR
Storage.prototype.get = function(key) {
var fromStorage = localStorage.getItem(key ? key : this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
your key should be incrementing, but your storage.get is hard coded to a specific key so you'll never be able to retrieve them through its get method.
You should also verify that the method is being invoked
You could try a string vs a number as a key
storage.set("topic_" + key, ticket);
// alert("topic set for topic_" + key);
// retrieve and test data storage
// var data = localStorage.getItem("topic_" + key);
// alert("from storage:\n\n" + JSON.stringify(data));
key++;
Use F12 to review localStorage or simply test the data that is stored
function test(){
if (localStorage.length == 0)
alert("no items in localStorage");
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var value = localStorage.getItem(key);
alert("storage [" + key + "] = " + value);
}
}

i want json array like["ajsa","ajhsahs"]

function createJSON() {
jsonObj = [];
$("input[class=email]").each(function () {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item["title"] = id;
item["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
I tried this but I want json array like ["ajsa","ajhsahs"]. How can achieve this? I tried to do it with key but I don't need key I only need value. The javascript array should should be converted to json array.
what you mean when you say value? use this for array of emails:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function () {
var email = $(this).val();
jsonObj.push(email);
});
console.log(jsonObj);
//and if you want it in string:
var stringObj = JSON.stringify(jsonObj);
return jsonObj;
}

Categories