如何将数组的特定对象分配到另一个对象数组?

时间:2016-11-02 07:30:18

标签: javascript angularjs json

我有一些名为ticket的对象,我想从诸如number,desc和state之类的票证中选择一些特定的对象,并将它们分配给新的对象数组,例如myarr。我正在编写下面的代码,但它说数字未定义。我做错了什么?

$scope.myarr=[{

  number:"",
  desc:"",
  state:""
  }

 ];


 for(var i=0;i<$scope.tickets.length;i++){

  $scope.myarr[i].number=$scope.tickets[i].number;
  $scope.myarr[i].desc=$scope.tickets[i].short_description;
  $scope.myarr[i].state=$scope.tickets[i].state;

 }

3 个答案:

答案 0 :(得分:1)

你需要做这样的事情。

$scope.myarr=[];
for(var i=0;i<$scope.tickets.length;i++){
  //Your Conditions
   var object={
      "number":$scope.tickets[i].number,
      "desc" :$scope.tickets[i].short_description,
      "state":$scope.tickets[i].state
   }
   $scope.myarr.push(object);
}

答案 1 :(得分:0)

$scope.myarr = [];
angular.forEach($scope.tickets, function(ticket) {
  this.push({number:ticket.number, state: ticket.state});
}, $scope.myarr);

答案 2 :(得分:0)

如果您不需要支持IE&lt; 9,有一个方便的函数map,在这种情况下很有用

$scope.myarr = $scope.tickets.map(function(ticket) {
  // return the element to be inserted in the new array
  return {
    number: ticket.number,
    desc: ticket.short_description,
    state: ticket.state
  };
});