gpt4 book ai didi

javascript - 按值对 JSON 进行分组

转载 作者:数据小太阳 更新时间:2023-10-29 04:00:31 24 4
gpt4 key购买 nike

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

这是 codepen这是JSON

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

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

我敢肯定这可能非常简单,但我绝对不是 JavaScript 专家。任何帮助将不胜感激!

最佳答案

假设,JSON 输出是

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

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


演示:

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

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

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

关于javascript - 按值对 JSON 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38575721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com