我需要对一组对象进行排序,并将具有相同键/值对的对象推送到新数组。
我正在整理的对象是足球运动员。 我拥有一系列对象中的所有玩家,并希望将每个位置推入他们自己的数组中。
防爆。 每个对象都有一个“位置”键,因此任何具有“QB”值的对象“position”的对象都应该被推入一个新的数组“Quarterbacks”。
这是迄今为止的代码 - 它是在Angular中所以我首先将所有玩家保存到变量“Roster”中,然后需要将玩家按位置分隔成单独的阵列,以保持所有玩家的位置。
angular.module('clientApp') .controller('PlayersCtrl', function ( $scope, Player ) { // $scope.players = Player.getList().$object; var Roster = Player.getList().$object; console.log(Roster); });虽然我有兴趣学习如何在一个函数中将所有位置推入自己的数组中,但我也想知道如何在一个位置执行此操作。 就像如何将所有四分卫从名册推到一个新的四分卫阵容。
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.
最满意答案
如果要为每个数组定义一个单独的数组,则可以使用switch语句。
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; } } }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; } } }
更多推荐
发布评论