我的 JSON 看起来像这样:
json = [
{
type: "big"
date: "2012-12-08"
qty: 6
}
{
type: "small"
date: "2012-12-08"
qty: 9
}
{
type: "big"
date: "2012-12-15"
qty: 4
}
{
type: "small"
date: "2012-12-07"
qty: 7
}
{
type: "small"
date: "2012-11-07"
qty: 3
}
]
我想做的是将每个分组/合并type
有一个date
同年同月(前 7 个字符)date
字符串)并得到它们的总和qty
'是。输出应如下所示:
json = [
{
type: "big"
date: "2012-12"
qty: 10
}
{
type: "small"
date: "2012-12"
qty: 16
}
{
type: "small"
date: "2012-11"
qty: 3
}
]
我在这里发现了几个类似的问题,但还没有遇到一个完全符合我的要求的问题。我已经尝试过从不同示例借用的大量代码,但似乎无法完全获得我需要的结果。我现在不在家,因此我无法粘贴我目前尝试过的任何代码,但我正在寻求帮助,希望能得到答案/解决方案以供稍后测试
这可以通过创建一个自定义对象来轻松处理,该对象具有以您的唯一组合命名的属性(即类型+日期的前 7 个)。
循环遍历您的数组并检查您的“holder”对象是否具有以您的唯一标识符命名的现有属性。如果已有该属性,则增加数量,否则添加新项目。
支架完全构建后,清除阵列,然后循环遍历支架的属性并将它们推回阵列。
var holder = {};
var json = [
{
type: "big",
date: "2012-12-08",
qty: 6
},
{
type: "small",
date: "2012-12-08",
qty: 9
},
{
type: "big",
date: "2012-12-15",
qty: 4
},
{
type: "small",
date: "2012-12-07",
qty: 7
},
{
type: "small",
date: "2012-11-07",
qty: 3
}
];
json.forEach(function(element) {
var identifier = element.type + element.date.slice(0, 7);
if (holder[identifier]) {
holder[identifier].qty += element.qty;
} else {
holder[identifier] = element;
};
});
json = [];
for(var identifier in holder) {
json.push(holder[identifier]);
}
console.log(json);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)