简体   繁体   English

在对象数组中排序和推送对象

[英]sorting and pushing objects in an array of objects

sorry for the lack of code — but this is a pretty straight forward javascript question. 很抱歉缺少代码-但这是一个非常简单的javascript问题。

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". 每个对象都有一个键“ position”,因此任何键“ position”的值为“ QB”的对象都应推入新数组“ Quarterbacks”。

What's the right way to sort through objects and push them into a new array that would work for my scenario? 什么是对对象进行排序并将其推入适用于我的场景的新数组的正确方法?

You can create an index object that contains all the positions you've seen so far and then accumulate an array of players for each position: 您可以创建一个索引对象,其中包含到目前为止您所看到的所有位置,然后为每个位置累积一个玩家数组:

 var data = [ {position: "quarterback", name: "Bob"}, {position: "center", name: "Jim"}, {position: "quarterback", name: "Ted"}, ]; var positions = {}; data.forEach(function(item) { if (!(item.position in positions)) { positions[item.position] = []; } positions[item.position].push(item); }); log(positions); function log(x) { var div = document.createElement("div"); div.innerHTML = JSON.stringify(x); document.body.appendChild(div); } 

Or you could make this into a generic grouping function like this: 或者,您可以将其变成一个通用的分组函数,如下所示:

 var data = [ {position: "quarterback", name: "Bob"}, {position: "center", name: "Jim"}, {position: "quarterback", name: "Ted"} ]; function groupData(data, key) { var results = {}; data.forEach(function(item) { console.log(item); var value = item[key]; if (!(value in results)) { results[value] = []; } results[value].push(item); }); return results; } log(groupData(data, "position")); function log(x) { var div = document.createElement("div"); div.innerHTML = JSON.stringify(x); document.body.appendChild(div); } 

You can use Array.prototype.forEach : 您可以使用Array.prototype.forEach

 var data = [ { position: "quarterback", name: "Bob" }, { position: "center", name: "Jim" }, { position: "quarterback", name: "Ted" }, ]; var dataByPositions = {}; data.forEach(function(x) { dataByPositions[x.position] = dataByPositions[x.position] || []; dataByPositions[x.position].push(x); }); // Demonstration purposes only: document.body.innerHTML = "<pre>" + JSON.stringify(dataByPositions, null, 4) + "</pre>"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM