user1187282 user1187282 - 3 months ago 17
AngularJS Question

Generic foreach Loop in Javascript

I'm stuck with foreach loop , i don't know the column Name so i can't do

value.Job
, and i need to display all the colums with it specific data

angular.forEach(data, function(value, key) {
console.log( 'the Object N° ' + i );
'maybe another loop for all the column
console.log( 'the column name is + ': ' + value ??);
});


the result should be like :

the Object N° 1
the column name is Name : Matt
the column name is Job : Teacher

the Object N° 2
the column name is Name : Alice
the column name is Job : Doctor


Any ideas here !

I want to see both the options for JavaScript and AngularJs forEach.

Answer

Yes, you can use a for...in loop to enumerate all the keys in an object as follows

var data = [
  {Name: "Matt", Job: "Teacher"},
  {Name: "Alice", Job: "Doctor"}];

data.forEach(function(e,i){
  console.log(i);
  for(var key in e){
      console.log(key + ':' + e[key] ); 
  }
});

Note that ive used Array.forEach, but angular.forEach will have much the same structure.

Comments