Cant access variable inside of firebase gotData() function outside - javascript

I want to get the value of power_level value on the last line of the below mentioned code but it is not showing anything. I need that value for further use what to do.
var config = {
//
};
firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref("power");
ref.on("value", gotData, errData);
var power_level;
function gotData(data) {
var power = data.val();
// Grab the keys to iterate over the object
var keys = Object.keys(power);
console.log(keys);
for (var i = keys.length - 1; i < keys.length; i++) {
var key = keys[i];
// Look at each fruit object!
var power_level = power[key];
console.log(power_level);
}
}
console.log(power_level);

The reason you don't get the value on the last line is because it is asynchronous. Basically you do ref.on and it runs the gotData() function if (and more importantly WHEN) it is successful, but your last console.log() runs regardless of whether gotData() is finished.
An easy way to handle this is by defining a separate function which takes power_level as a parameter and handles the power_level, and run that at the end of gotData().
Something like this:
var config = {
//
};
firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref("power");
ref.on("value", gotData, errData);
var power_level;
function gotData(data) {
var power = data.val();
// Grab the keys to iterate over the object
var keys = Object.keys(power);
console.log(keys);
for (var i = keys.length-1; i < keys.length; i++) {
var key = keys[i];
// Look at each fruit object!
var power_level = power[key];
console.log(power_level);
////////// call handlePowerlevel here to handle logic further
handlePowerlevel(power_level)
}
}
function handlePowerlevel(pl) {
console.log(pl);
// actual logic
}

Related

is there way store functions looping through them and putting them in a object

how can i sotre these function in object , looping through all of them and putting them in my storeObject
var fn1 = function1();
var fn2 = function2();
var fn3 = function3();
var fn4 = function4();
const store = {
storeId : 1,
cache:{},
add:function(fn){
if(!fn.id){
fn.id = this.storeId++;
this.cache[fn.id] = fn;
return true;
}
}
}
for(let i = 0;i < 4;i++){
store.add ?; // i got stuck here what i should i do in order to store my functions using the for loop
}
You need to wrap everything in an array for you to loop through. Like an array of Object
Becomes:
var fxns = [
{fn1: function1()},
{fn2: function2()},
{fn3: function3()},
{fn4: function4()}
]
for(let i = 0;i < fxns.length;i++) {
}

How to iterate through firebase object childeren

I am new to firebase and javascript but I am trying to iterrate through my firebase database which really just has 1 object and some childeren under it. I followed some tutorials but feel like im in a rabbit hole right now. I only get the top levels back and not the childeren
This is what i tried:
var ref = database.ref('Exercise');
ref.on('value', gotData, errData);
function writeData(){
firebase.database().ref("Exercise").set({
nameExercise: exerciseName.value,
setAm: setAmount,
// setAm: {
// HoeveelheidArr,
// Gewicht,
//}
repetitie: Gewicht,
hoeveelheidKilogram:Gewicht,
});
}
var ref = database.ref('Exercise');
ref.on('value', gotData, errData);
function gotData(data){
//console.log(data.val());
var exercise = data.val();
var keys = Object.keys(exercise);
console.log(keys);
for( var i = 0; i < keys.length; i++){
var k = keys[i];
var exerciseID = scores[k].nameExercise.value;
var sets = scores [k].setAm.value;
var reps = scores[k].repetitie.value;
var kg = scores [k].hoeveelheidKilogram.value;
console.log(exerciseID, sets,reps,kg);
}
}
function errData(err){
console.log('Error!');
console.log(err);
}
the write function works well but not the gotData where im trying to display every value of the object in the console:
but all im getting back is teh variable names from the writeData function. Do you see what i do wrong?
As far as I can see you have only a single exercise under /Exercise, which means that the for( var i = 0; i < keys.length; i++){ loop is not needed.
An example of how to access/log various parts of your JSON:
function gotData(data){
var exercise = data.val();
console.log(exercise);
console.log(exercise.hoeveelheidKilogram);
exercise.hoeveelheidKilogram.forEach(function(value) {
console.log(value);
});
}

How store value in variable in for loop using javascript

I am using for loop in javascript and store value in multiple variables.
var friend_id1 = '';
var friend_id2 = '';
var friend_id3 = '';
FB.api('/me/friends', function(response) {
if(response.data) {
obj = response.data
obj = shuffle(obj);
a = 3;
for(x = 1; x <= obj.length; x++){
friend_id[x] = obj[x].id;
if(x >= a) break;
}
} else {
alert("Error!");
}
});
if i replace friend_id[x] to friend_id1 i will get user id. But i want store values in multiple variables.
You're trying to save the values to an array:
friend_id[x] = obj[x].id;
But you didn't declare an array, you have no array variable called friend_id. Instead, you have multiple variables with numbered names.
Just declare the array as you want to use it:
var friend_id = [];
Or, more aptly named:
var friend_ids = [];
And more properly used:
friend_ids.push(obj[x].id);

js Array undefined after json declaration

I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}

Issue with javascript array variables

I am using javascript in my app which is a rhino javascript engine. I like to use array for an array.
The following code is my actual working code.
while (input.hasNext()) {
var data = input.next();
var new_data = {};
var i = 0;
while(i<data.get('total_entries')){
new_data.entries = data.get('total_entries');
new_data.id = data.get('out').get(i).get('id');
output.write(new_data);
i++;
}
}
I need to create array for new_data[].
while (input.hasNext()) {
var data = input.next();
var new_data[] = {};
var i = 0;
while(i<data.get('total_entries')){
new_data[i].entries = data.get('total_entries');
new_data[i].id = data.get('out').get(i).get('id');
output.write(new_data[i]);
i++;
}
}
But its not working. So, help me to create array variable in it.
Thanks.
You mean something like this:
while (input.hasNext()) {
var data = input.next();
var new_data = [];
var i = 0;
while(i<data.get('total_entries')){
new_data.push({entries: data.get('total_entries'), id: data.get('out').get(i).get('id')});
output.write(new_data[i]);
i++;
}
}
var new_data[] = {};
First of all, that's invalid JavaScript.
new_data[i]
Looks like you want new_data to be an array of objects. Why not declare it as one and add objects on every iteration of the while loop:
var new_data = [];
while(...){
new_data.push({
entries: ...
id: ...
});
}

Categories

Resources