gpt4 book ai didi

javascript - 是否可以使用 underscore.js 对 JSON 数据进行分组?

转载 作者:行者123 更新时间:2023-12-02 16:22:18 26 4
gpt4 key购买 nike

假设我有这些数据,它是查询的结果。

[
[
{
"brgy_locat": "Kauswagan",
"countlow": 8
},
{
"brgy_locat": "Katugasan",
"countlow": 24
},
{
"brgy_locat": "Comagascas",
"countlow": 3
},
{
"counthigh": 7,
"brgy_locat": "Barangay 9"
},
[
{
"brgy_locat": "Barangay 11",
"countmedium": 1
}
],
[],
[],
[],
[
{
"brgy_locat": "Mabini",
"countmedium": 1
}
],
[
{
"counthigh": 27,
"brgy_locat": "Barangay 6"
},
{
"counthigh": 3,
"brgy_locat": "Mabini"
},
{
"counthigh": 2,
"brgy_locat": "Barangay 2"
},
{
"counthigh": 7,
"brgy_locat": "Barangay 9"
},
{
"counthigh": 17,
"brgy_locat": "Comagascas"
},
{
"counthigh": 1,
"brgy_locat": "Tolosa"
},
{
"counthigh": 33,
"brgy_locat": "Barangay 7"
}
]
]
]

我希望它按 brgy_locat 分组,并对 countlowcountmediumcounthigh 中的所有值求和如果 brgy_locat 相同。不知怎的,像这样:

[
{
"brgy_locat": "Kauswagan",
"countlow": 8,
"countmedium": 1,
"counthigh": 5
}
]

以上值只是示例。看看这个JSFiddle我做的。

最佳答案

我看到了你的 fiddle ,你应该添加一个flatten函数,并让你的sum函数将current转换为0。 未定义

你可以做这样的功能:

function sum(numbers) {
return _.reduce(numbers, function (result, current) {
return result + parseFloat(current || 0);
}, 0);
}


function summarize(data) {
var summary = _(data).chain()
.flatten()
.groupBy("brgy_locat")
.map(function (value, key) {
return {
brgy: key,
low: sum(_(value).chain().pluck("countlow").value()),
medium: sum(_(value).chain().pluck("countmedium").value()),
high: sum(_(value).chain().pluck("counthigh").value())
}
})
.value();

return summary;
}

当您调用它传递您作为示例提供的数据时,结果将是您所要求的......

关于javascript - 是否可以使用 underscore.js 对 JSON 数据进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29002545/

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