使用杠杆作业发布API,我得到按位置排序的
JSON结果,我正在尝试弄清楚如何在结果中按“团队”对所有结果进行分组,例如
Shopify职业页面.
我尝试在codepen的第38行添加以下内容以尝试获取团队值,但它没有按预期输出(我每行收到一个字母,这没有帮助):
for (var x in _data[i].postings[j].categories.team)
我敢肯定它可能是超级简单的东西,但我绝对不是一个javascript的家伙.任何帮助将非常感激!
解决方法
假设,JSON输出是
outJSON= [ { team: "TeamA",name: "Ahmed",field3:"val3" },{ team: "TeamB",field3:"val43" },{ team: "TeamA",field3:"val55" },]
然后在下面的DEMO中查看groupBy函数:
演示:
outJSON= [ {team: "TeamA",field3:"val3"},{team: "TeamB",field3:"val43"},{team: "TeamA",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);
然后,如果您想循环遍历类别(团队),请获取数组中的所有类别:
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}.`) }) });