通过排序对象的数组,推动具有相同的键/值对的对象到一个新的数组 [英] Sort through an array of objects and push objects with the same key/value pair to a new array

查看:175
本文介绍了通过排序对象的数组,推动具有相同的键/值对的对象到一个新的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过对象数组进行排序,并推动具有相同的键/值对的对象到一个新的数组。

我整理过的对象是足球运动员。我有对象的数组所有玩家,并希望每个位置推入各自为阵。

防爆。每个对象都有位置,所以任何以QB的价值目标的关键位置的关键应该推到一个新的数组四分卫。

这里的code迄今为止 - 它在角,所以我首先玩家保存到一个变量花名册,并从那里需要通过位置成为持有该位置所有球员单独阵列分离球员

\r
\r

angular.module('clientApp')\r
  .controller('PlayersCtrl',函数(\r
    $范围,\r
    播放机\r
  ){\r
    // $ scope.players = Player.getList()$对象。\r
    无功名册= Player.getList()$对象。\r
\r
    的console.log(名册);\r
    \r
});

\r

\r
\r

虽然我有兴趣学习如何做到这一切的一切推到位置自己阵一个功能,我也想弄清楚如何做到这一点的一个位置。怎么样从名册上推所有四分卫逼到四分卫的新数组。


解决方案

如果要定义为每一个单独的数组,你可以使用switch语句。

  VAR名册= [
  {球员:奔的位置:QB,月薪:1000},
  {球员:布朗,立场:WR,月薪:1200},
  {球员:兰德里的位置:QB,工资:800}
];变种qbArray = [];
变种wrArray = [];功能parseIntoArrayByPosition(){
  对于(VAR I = 0; I< roster.length;我++){
    VAR位置=名册[I] .POSITION;    开关(位置){
      案QB:
        qbArray.push(名单[I]);
        打破;
      案WR:
        wrArray.push(名单[I]);
        打破;
    }
  }
}

I need to sort through an array of objects and push objects with the same key/value pair to a new array.

The objects I'm sorting through are football players. I have all players in an array of objects and want to push each position into their own array.

Ex. each object has a key of "position" so any object with the value of "QB" for the key "position" should be pushed into a new array "Quarterbacks".

Here's the code so far — it's in Angular so I first save all the players to a variable "Roster" and from there need to separate players by position into separate arrays that hold all players for that position.

angular.module('clientApp')
  .controller('PlayersCtrl', function (
    $scope,
    Player
  ) {
    // $scope.players = Player.getList().$object;
    var Roster = Player.getList().$object;

    console.log(Roster);
    
});

Although i'm interested in learning how to do this all in one function that pushes all positions into their own array, i'd also like to figure out how to do it for one position. Like how to push all the quarterbacks from the Roster into a new array of just quarterbacks.

解决方案

If you are defining a separate array for each you could use a switch statement.

var roster  = [
  {player: "Ben", position: "qb", salary: 1000},
  {player: "Brown", position: "wr", salary: 1200},
  {player: "Landry", position: "qb", salary: 800}
];

var qbArray = [];
var wrArray = [];

function parseIntoArrayByPosition() {
  for (var i = 0; i < roster.length; i++) {
    var position = roster[i].position;

    switch (position) {
      case "qb":
        qbArray.push(roster[i]);
        break;
      case "wr":
        wrArray.push(roster[i]);
        break;
    }
  }
}

这篇关于通过排序对象的数组,推动具有相同的键/值对的对象到一个新的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆