按值对JSON进行分组 [英] Grouping JSON by values

查看:120
本文介绍了按值对JSON进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 Shopify careers page.

这是< a href =http://codepen.io/anon/pen/jAxXAo =noreferrer> codepen ,这里是 JSON

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

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):

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



<我确信这可能是超级简单的东西,但我绝对不是一个javascript的家伙。任何帮助将不胜感激!

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

推荐答案

假设,JSON输出

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


]

然后在下面的DEMO中查看 groupBy 函数:

Then see the groupBy function in the DEMO below:

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"]

然后:

  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}.`)
       })
  }); 

这篇关于按值对JSON进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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