2 回答
TA贡献2003条经验 获得超2个赞
var arr = {
"counts": [
[{
"xcount": 0.0,
"ycount": 0.0,
"month": 4
},
{
"xcount": 0.0,
"ycount": 0.0,
"month": 5
},
{
"xcount": 0.0,
"ycount": 2.85,
"month": 6
},
{
"xcount": 8.85,
"ycount": 0.0,
"month": 6
},
{
"xcount": 10.17,
"ycount": 0.0,
"month": 7
},
{
"xcount": 0.0,
"ycount": 2.85,
"month": 7
},
{
"xcount": 12.0,
"ycount": 0.0,
"month": 8
},
{
"xcount": 0.0,
"ycount": 2.85,
"month": 8
},
{
"xcount": 0.0,
"ycount": 2.85,
"month": 9
},
{
"xcount": 11.0,
"ycount": 0.0,
"month": 9
}
]
]
}
arr.counts[0] = arr.counts[0].reduce((acc, cv, i, arr) => {
if (!acc[cv.month]) {
acc[cv.month] = cv;
} else {
acc[cv.month].xcount += cv.xcount
acc[cv.month].ycount += cv.ycount
}
if (i === arr.length - 1) {
return Object.keys(acc).map(key => acc[key])
} else {
return acc;
}
}, {});
console.log(arr.counts[0]);
使用该reduce函数,我们使用月份号作为键创建一个临时对象。这使我们能够跟踪唯一条目。当我们找到一个重复的月份时,我们将xcountand加ycount在一起。一旦我们到达列表的末尾,我们就会返回映射到它们的值的临时对象的键。导致列表仅包含唯一月份。
TA贡献1777条经验 获得超3个赞
正如我从您的问题中了解到的那样,要删除重复的月份,如果是这种情况,这是我上面的建议。
更新:了解您关于通过 xcount、ycount 组合的观点,并添加了必要的更改。
var arr = {
"counts": [
[
{
"month": 4,
"xcount": 0,
"ycount": 0
},
{
"month": 5,
"xcount": 0,
"ycount": 0
},
{
"month": 6,
"xcount": 0,
"ycount": 2.85
},
{
"month": 6,
"xcount": 8.85,
"ycount": 0
},
{
"month": 7,
"xcount": 10.17,
"ycount": 0
},
{
"month": 7,
"xcount": 0,
"ycount": 2.85
},
{
"month": 8,
"xcount": 12,
"ycount": 0
},
{
"month": 8,
"xcount": 0,
"ycount": 2.85
},
{
"month": 9,
"xcount": 0,
"ycount": 2.85
},
{
"month": 9,
"xcount": 11,
"ycount": 0
}
]
]
};
var tmpMonths = [];
var tmpObjects = {};
var results = [];
for (var i=0;i<arr.counts[0].length;i++) {
var obj = arr.counts[0][i];
var key = "month_" + obj.month;
if (obj.month && tmpMonths.indexOf(obj.month)===-1) {
tmpMonths.push(obj.month);
tmpObjects[key] = obj;
results.push(obj);
} else {
tmpObjects[key] = {
month: obj.month,
xcount: obj.xcount + tmpObjects[key]["xcount"],
ycount: obj.ycount + tmpObjects[key]["ycount"],
};
}
}
arr.counts[0] = Object.values(tmpObjects);
console.log(JSON.stringify(arr));
添加回答
举报