foreach loop in angularjs
Solution 1
Questions 1 & 2
So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :
var values = {name: 'misko', gender: 'male'};
Angular will take each value one by one the first one is name, the second is gender.
If your object to iterate on is an array (also possible), like this :
[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }]
Angular.forEach will take one by one starting by the first object, then the second object.
For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :
var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male
So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'
If this time you display an array, like this :
var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]
So then value is your object (collection), and key is the index of your array since :
[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
1: { "Name" : "Linda", "Password" : "lindatheQueen" }}
I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/
Debugging your code
The problem seems to come from the fact $http.get()
is an asynchronous request.
You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach
without waiting the answer of your JSON.
You need to include the loop in the success function
var app = angular.module('testModule', [])
.controller('testController', ['$scope', '$http', function($scope, $http){
$http.get('Data/info.json').then(function(data){
$scope.data = data;
angular.forEach($scope.data, function(value, key){
if(value.Password == "thomasTheKing")
console.log("username is thomas");
});
});
});
This should work.
Going more deeply
The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.
You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.
Solution 2
you have to use nested angular.forEach loops for JSON as shown below:
var values = [
{
"name":"Thomas",
"password":"thomas"
},
{
"name":"linda",
"password":"linda"
}];
angular.forEach(values,function(value,key){
angular.forEach(value,function(v1,k1){//this is nested angular.forEach loop
console.log(k1+":"+v1);
});
});
Solution 3
The angular.forEach()
will iterate through your json
object.
First iteration,
key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}
Second iteration,
key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }
To get the value of your name
, you can use value.name
or value["name"]
. Same with your password
, you use value.password
or value["password"]
.
The code below will give you what you want:
angular.forEach(json, function (value, key)
{
//console.log(key);
//console.log(value);
if (value.password == "thomasTheKing") {
console.log("username is thomas");
}
});
Solution 4
In Angular 7 the for loop is like below
var values = [
{
"name":"Thomas",
"password":"thomas"
},
{
"name":"linda",
"password":"linda"
}];
for (let item of values)
{
}
Solution 5
Change the line into this
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
angular.forEach(values, function(value, key){
console.log(key + ': ' + value.Name);
});
Related videos on Youtube
Pragam Shrivastava
I am a hobbyist programmer and currently working in CTS.
Updated on August 01, 2022Comments
-
Pragam Shrivastava almost 2 years
I was going through the
forEach
loop
inAngularJS
. There are few points that I did not understood about it.- What is the use of the iterator function? Is there any way to go without it?
- What is the significance of the key and value as shown below?
angular.forEach($scope.data, function(value, key){});
PS: I tried to run this function without the arguments and it did not work.
Here's my
json
:[ { "Name": "Thomas", "Password": "thomasTheKing" }, { "Name": "Linda", "Password": "lindatheQueen" } ]
My
JavaScript
file:var app = angular.module('testModule', []); app.controller('testController', function($scope, $http){ $http.get('Data/info.json').then( function(data){ $scope.data = data; } ); angular.forEach($scope.data, function(value, key){ if(value.Password == "thomasTheKing") console.log("username is thomas"); }); });
Another question: Why the function above does not enter on if condition and print "username is thomas" in the console?
-
Tom about 9 yearsBecause you're not waiting for the
success
to happen of your$http.get()
, thus, whenangular.forEach()
happens,$scope.data
is still undefined. -
Pragam Shrivastava about 9 yearsIs there any specific way to hold the execution of the code untill the json is loaded
-
Israel Ocbina about 7 yearsChange the line into this angular.forEach(values, function(value, key){ console.log(key + ': ' + value.Name); });
-
Drew over 8 yearsColin B (profile Here . ) wanted to comment that
success
anderror
have been deprecated. Usingthen
method instead ofsuccess
is suggested. Now, @Colin, go out and Answer a few questions to get 50 rep ! :P -
Kyle Baker about 7 yearsAsync is not parallel. For parallel, he'll need webworkers, not promises. Tiny bit pedantic, but worth stopping misinformation on that whenever it happens.
-
Kyle Baker about 7 yearsNo, you would use a single loop, and frankly, in this case, you should just use the native forEach(), a la
values.forEach(object => console.log(
${object.name}: ${object.password}))
. -
sebastienbarbier about 7 yearsThanks @KyleBaker, I updated this answer, you're right "parallel" was an abuse of language.
-
Israel Ocbina about 7 yearsJust change the line console.log(key + ': ' + value); INTO console.log(key + ': ' + value.Name);
-
Nikson about 6 years@sebastienbarbier can you please help me to solve this stackoverflow.com/questions/50100381/…
-
Badri Paudel about 2 yearsAngular version 2.x or later is completely different than angularjs [< 2 ], they've even named differently. Even though plain JS is always there, Angularjs and Angular are completely different in terms of many things.