如何在数组中推送对象列表的特定字段

时间:2015-06-03 09:18:51

标签: angularjs

我的问题是只保留对象数组中的特定字段值,在我的例子中,它是FirstName,LastName,PhoneNumber,Department,EmailId。对象数组$ scope.devices中的单个对象有很多字段,但我想保留所有对象的上述字段值。

 // Angularjs part ,devices is the objecctlist    
    var deviceArray = []; 
           for(var entry in  $scope.devices)  {
           deviceArray.push({FirstName: entry.FirstName,
                             LastName:  entry.LastName,
                             PhoneNumber: entry.PhoneNumber,
                             EmailId : entry.EmailId,
                             Department : entry.Department,
                             });`
           };
           $log.debug('deviceArray :', deviceArray) //deviceArray : []

3 个答案:

答案 0 :(得分:1)

尝试:

var deviceArray = [], fields = "FirstName,LastName,PhoneNumber,Department,EmailId";

angular.forEach($scope.devices, function(item){
    var temp = {};
    angular.forEach(fields.split(/[, ]+/), function(key){
        temp[key] = item[key]
    });
    deviceArray.push(temp)
});

console.log(deviceArray)

答案 1 :(得分:1)

如果您正在使用角度,则最好使用角度forEach

您可以使用angular forEach

以下列方式执行此操作


var deviceArray = [];

angular.forEach($scope.devices,function(entry,key){     

      deviceArray.push({    
                            FirstName: entry.FirstName,
                            LastName:  entry.LastName,
                            PhoneNumber: entry.PhoneNumber,
                            EmailId : entry.EmailId,
                            Department : entry.Department,
                      }); 

    })
中的

将提供索引编号,而不是Object.Using该索引,您必须访问该数组中的实际对象。

var deviceArray = [];
          for(var entry in  $scope.devices){
            deviceArray.push({
                              FirstName: $scope.devices[entry].FirstName,
                              LastName:  $scope.devices[entry].LastName,
                              PhoneNumber: $scope.devices[entry].PhoneNumber,
                              EmailId : $scope.devices[entry].EmailId,
                              Department : $scope.devices[entry].Department,
                            });
          }

答案 2 :(得分:0)

在表单for (var entry in $scope.devices)中,您将数组的键作为对象循环,因此entry为0,1,等等。

您应该对数组使用for (var i = 0; i < ...)循环:

 var deviceArray = [];
 for (var i = 0; i < $scope.devices.length; i++) {
     var entry = $scope.devices[i];
     deviceArray.push({
         FirstName: entry.FirstName,
         LastName: entry.LastName,
         PhoneNumber: entry.PhoneNumber,
         EmailId: entry.EmailId,
         Department: entry.Department,
     });
 };

但在这种情况下,使用Array.prototype.map:

是最佳选择
var deviceArray = $scope.devices.map(function(entry) {
    return {
         FirstName: entry.FirstName,
         LastName: entry.LastName,
         PhoneNumber: entry.PhoneNumber,
         EmailId: entry.EmailId,
         Department: entry.Department,
     };
});