Javascript和AngularJs中的通用foreach循环

时间:2016-09-01 08:52:54

标签: javascript angularjs

我坚持使用foreach循环,我不知道专栏名称,所以我无法做到 value.Job,我需要显示所有列的特定数据

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  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

这里有任何想法!

我想看看JavaScript和AngularJs forEach的两个选项。

3 个答案:

答案 0 :(得分:5)

是的,您可以使用for...in循环来枚举对象中的所有键,如下所示



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] ); 
  }
});




请注意,我使用了Array.forEach,但angular.forEach的结构大致相同。

答案 1 :(得分:1)

你也可以试试这个:

data.forEach(function(item){
      Object.keys(item).forEach(function(key){
            console.log(key + ":" + item[key]);
      });
   });

答案 2 :(得分:-1)

  

尝试以下两个选项:通用JavaScript和AngularJs

//AngularJS for each 
var app = angular.module("app", []);
var values = [{'name': 'Jimi', 'gender': 'male'},{'name': 'Peter', 'gender': 'male'},{'name': 'Bob', 'gender': 'male'}];
app.controller('forEachController', ['$scope', function ($scope) {
        $scope.names = [];
        //Angular for each
        console.log("AngularJs Output");
        angular.forEach(values, function (value, key) {
            angular.forEach(value, function (val, k) {
              console.log(k + ":" + val);
            });
        });  
 }]);
console.log("JavaScript Output");
//Generic JavaScript for each
values.forEach(function(item){
  Object.keys(item).forEach(function(key){
    console.log(key + ":" + item[key]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="forEachController"></div>