[英]Is it possible to group this JSON data using underscore.js?
假設我有此數據,它是查詢的結果。
[
[
{
"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
countlow
,如果brgy_locat
相同, countmedium
countlow
, countmedium
和counthigh
所有值相加。 像這樣:
[
{
"brgy_locat": "Kauswagan",
"countlow": 8,
"countmedium": 1,
"counthigh": 5
}
]
上面的值僅是示例。 看看我制作的這個JSFiddle 。
第一次,我誤解了這個問題。 您仍然想展平,並且仍然可以使用groupby。 我發現在此使用_.each
和index參數非常有用。 這應該為您做:
var temp = _.chain(data)
.flatten()
.groupBy('brgy_locat')
.each(function(eachObj,index) {
if (!result.findWhere({ 'brgy_locat': index })) {
var newObj = {
'brgy_locat': index,
countlow: _.reduce(eachObj, function(memo, obj) {
if (!obj.countlow) return memo;
return memo + obj.countlow;
},0),
countmedium: _.reduce(eachObj, function(memo, obj) {
if (!obj.countmedium) return memo;
return memo + obj.countmedium;
},0),
counthigh: _.reduce(eachObj, function(memo, obj) {
if (!obj.counthigh) return memo;
return memo + obj.counthigh;
},0)
};
result.push(newObj);
}
});
我看到了您的小提琴,您應該添加一個flatten
函數,並在undefined
current
時使sum
函數將其轉換為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;
}
當您調用它傳遞您作為示例提供的數據時,結果將是您所要求的...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.