Javascript 按值对 JSON 进行分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38575721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:36:36  来源:igfitidea点击:

Grouping JSON by values

javascriptjqueryjsongrouping

提问by robotsmeller

Using the Lever job posting API, I'm getting JSON results sorted by location, and I'm trying to figure out how to group all those results by "team" within the results, like the Shopifycareers page.

使用 Lever 职位发布 API,我得到了按位置排序的 JSON 结果,我试图弄清楚如何在结果中按“团队”对所有这些结果进行分组,例如Shopify职业页面。

Here is the codepenand here is the JSON

这是代码笔,这是JSON

I tried adding the following on line 38 of the codepen to try to grab the team values, but it's not outputting as expected (I'm getting one letter per line, which isn't helpful):

我尝试在 codepen 的第 38 行添加以下内容以尝试获取团队值,但它没有按预期输出(我每行收到一个字母,这没有帮助):

for (var x in _data[i].postings[j].categories.team)

I'm sure it's probably something super simple, but I'm definitely not a javascript guy. Any help would be much appreciated!

我敢肯定这可能是超级简单的事情,但我绝对不是一个 javascript 人。任何帮助将非常感激!

回答by Abdennour TOUMI

Assume , the JSON output is

假设,JSON 输出是

outJSON= 
 [ {
      team: "TeamA",
      name: "Ahmed",
      field3:"val3"
  }, 
{
      team: "TeamB",
      name: "Ahmed",
      field3:"val43"
  }, 
{
      team: "TeamA",
      name: "Ahmed",
      field3:"val55"
  }, 


]

Then see the groupByfunction in the DEMO below:

然后看groupBy下面DEMO中的功能:



DEMO :

演示:

outJSON= [ {team: "TeamA",name: "Ahmed",field3:"val3"}, {team: "TeamB",name: "Ahmed",field3:"val43"}, {team: "TeamA",name: "Ahmed",field3:"val55"} ]

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
var groubedByTeam=groupBy(outJSON, 'team')
console.log(groubedByTeam);

Then , if you want to loop through categories (teams), get all categories in array :

然后,如果您想遍历类别(团队),请获取数组中的所有类别:

Object.keys(groubedByTeam) // return ["TeamA","TeamB"]

then :

然后 :

  Object.keys(groubedByTeam).forEach(function(category){

       console.log(`Team ${category} has ${groubedByTeam[category].length} members : `);
        groubedByTeam[category].forEach(function(memb,i){
              console.log(`---->${i+1}. ${memb.name}.`)
       })
  });