How store value in variable in for loop using javascript - 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);

Related

Issue populating an array of objects dynamically in javascript

I am facing an issue when populating an array of the object dynamically in javascript. I have this sample data as below:
I have to populate following arrays with the data from above:
c1_Arr = [];
c2_Arr = [];
var torontoObj = { arName: 'تورونتو', enName: 'Totonto', value: 0 };
var parisObj = { arName: 'باريس', enName: 'Paris', value: 0 };
var londonObj = { arName: 'لندن', enName: 'London', value: 0 };
Now I am looping through the data to set the values from data as:
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
if (data.Ind_ID === 101) {
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
I am getting this data in console:
Here I am getting the values of the object i.e. Ind_ID = 102 instead of the object values of Ind_ID = 101 (first object).
How to get the values of the required object using the Ind_ID?
The problem is because even though you have the if condition there but you are updating the value of the objects in the loop and since you have already pushed them objects you still have the reference in the main objects. They get overwritten.
Create the 3 objects (torontoObj, etc.) inside the loop.
Reference is getting updated in the second iteration (where Ind_ID is 102)
You should rather do
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
if (data.Ind_ID === 101) {
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
Your object values are getting updated even after being set inside the if loop, simply because, you're not limiting it from being updated.
You could probably do one of the following 2 things:
The simpler one:
Extract the values of Paris, London and Toronto fields of data only if the Ind
_ID is 101.
like this:
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
if (data.Ind_ID === 101) {
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
The more elegant one:
Extract the array element which only matches your condition, in other words filter.
var resultCount = results.features.length;
var data = results.features.filter(feature => feature.attributes.Ind_ID === 101);
parisObj.value = data[0].Paris;
londonObj.value = data[0].London;
torontoObj.value = data[0].Toronto;
console.log(c1_Arr);

Cant access variable inside of firebase gotData() function outside

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
}

Create Dynamic Object Javascript

i just wanted to create a Dynamic Object in JS, but the Object only saves the last Element of the foor loop. Heres my Code :
for(var i = 0; i < req.session.userObjekt.length; i++) {
var userObjekt = {
[req.session.userObjekt[i].User]: {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
}
};
}
When i output in the for loop i get the correct result (7 Users + Properties)
When i output out of the for loop, i only get the last User + Properties.
How to save all Elements from the for loop in my Object?
Thanks in advance.
Because you assign to your userObjekt a new object in each iteration. Move out your object declaration from the for loop body
var userObjekt = { };
for(var i = 0; i < req.session.userObjekt.length; i++) {
userObjekt[req.session.userObjekt[i].User] = {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
};
}
You can create an array outside of loop and just push the objects in it later on you can use the declared and filled array:
var objektArr = [];
for(var i=0; i<req.session.userObjekt.length; i++) {
var userObjekt = {
[req.session.userObjekt[i].User]: {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
},
};
objektArr.push(userObjekt);
}
console.log(objektArr);

Compare function variable against array loop

I'm attempting to compare the value passed through the function (val) with items in an array (data.category) in order to replace my hard-coded 'cat1' and 'cat2' in the if/else statement. What I ultimately want to do is assign the appropriate $scope.catName and $scope.info for the appropriate value associated in the array.
How do I modify my code to iterate and compare?
$scope.changeRankingView = function(val){
var categoriesArray = data.category;
var categoriesArrayLength = categoriesArray.length;
for (var i = 0; i < categoriesArrayLength; i++) {
if(val === 'cat1'){
$scope.catName = data.category[0].name;
$scope.info = data.category[0].info;
}
else if(val === 'cat2'){
$scope.catName = data.category[1].name;
$scope.info = data.category[1].info;
}
}
};
I'm not completely sure I followed, but I think this would do what you are asking:
$scope.changeRankingView = function(val) {
for (var i = 0; i < data.category.length; i++) {
if(val === data.category[i]){
$scope.catName = data.category[i].name;
$scope.info = data.category[i].info;
}
}
};
I used data.category directly, because it didn't seem like categoriesArray was adding anything useful.

How to write the key(passed in as an argument to the function) in the js object dynamically?

temp = temp[array[i]] = {name:value};
In the above snippet the name is actually a parameter to my function having a value first_name.
Here's the function.
function createHierarchy(obj, group, name, value){
console.log("group = "+group+"\nname ="+name)
var array = group.split(".");
var temp = obj;
var len = array.length;
for(var i = 0; i < len; i++) {
if(temp[array[i]] === undefined)
temp = temp[array[i]] = {name:value};
else
temp = temp[array[i]][name] = value;
}
return obj;
}
The object being dumped has the key name equal to the identifier passed not its dynamic value which was "first_name" .
What am i missing. Let me know if i should update something.
Actual output
name: "cafebabe"
Expected output
first_name : "cafebabe"
FYI
Call this function like
createHierarchy({}, 'personal_details', 'first_name', 'cafebabe')
This piece of code is incorrect, you can't use name as variable in a default value like that:
if(temp[array[i]] === undefined)
temp = temp[array[i]] = {name:value};
else
temp = temp[array[i]][name] = value;
Replace that with:
temp[array[i]] = temp[array[i]] || {}; // If `temp[array[i]]` doesn't exist, add it.
temp = temp[array[i]][name] = value; // Assign the `value`.
JavaScript does not allow variables to be used as object keys, in object literals. In this example:
{ name: value }
JavaScript interpreters will never look for a name variable. It will just use "name" as the key.
The only way to use variables as object keys, is via the bracket notation:
myObject[name]

Categories

Resources