从Array结果中获取两个文件

时间:2016-01-07 07:30:05

标签: javascript angularjs multidimensional-array

我的服务给出如下结果

$scope.ListOfPeople = [
    { PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
    { PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
    { PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
    { PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
    { PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
    { PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];

我需要自定义我的数据源,如下所示

$scope.output= [
    { PersonID: 10, FirstName: "John" },
    { PersonID: 11, FirstName: "James" },
    { PersonID: 12, FirstName: "Mary" },
    { PersonID: 13, FirstName: "Sandra" },
    { PersonID: 14, FirstName: "Shaun" },
    { PersonID: 15, FirstName: "Nicola" }
];

在angularjs

中执行此操作的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

您可以使用map来实现目标。请注意map创建新阵列。

$scope.output = $scope.ListOfPeople.map(function(item){
    return {
        PersonID: item.PersonID,
        FirstName: item.FirstName
    };
});

答案 1 :(得分:1)

我认为你不需要创建一个新阵列来重塑它的元素。只需从元素中删除不需要的属性即可。

//Iterate through the array
$scope.listOfPeople.forEach(function(obj){

    //Iterate through properties
    for (var property in obj) {
       if (['PersonId', 'FirstName'].indexOf(property) < 0)     //Delete anything you don't name here
          delete obj[property]; 
   }      

})