JavaScript - 如何计算JSON中的每个键值?
header('Content-Type: application/json');
使用此JSON格式:
[
{date: "2017-09-28", type: "line", count: 1},
{date: "2017-09-28", type: "line", count: 1},
{date: "2017-09-28", type: "dot", count: 1},
{date: "2017-09-26", type: "dot", count: 1}
]
或
最终,到:
[
{date: "2017-09-26", count: 1},
{date: "2017-09-28", count: 3}
]
答案 0 :(得分:1)
如果哈希不存在,您可以使用哈希表并创建新对象。稍后将计数值添加到组中。
var data = [{ date: "2017-09-28", type: "line", count: 1 }, { date: "2017-09-28", type: "line", count: 1 }, { date: "2017-09-28", type: "dot", count: 1 }, { date: "2017-09-26", type: "dot", count: 1 }],
hash = Object.create(null),
result = [];
data.forEach(function (o) {
if (!hash[o.date]) {
hash[o.date] = { date: o.date, dot_count: 0, line_count: 0 };
result.push(hash[o.date]);
}
hash[o.date][o.type + '_count'] += o.count;
});
result.sort(function (a, b) { return a.date.localeCompare(b.date); });
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)
您可能正在寻找array.prototype.reduce。
const test = [
{date: "2017-09-28", type: "line", count: 1},
{date: "2017-09-28", type: "line", count: 1},
{date: "2017-09-28", type: "dot", count: 1},
{date: "2017-09-26", type: "dot", count: 1}
];
let result = test.reduce((group, current) => {
let index = group.findIndex(ele => ele.date === current.date);
if (index === -1) {
group.push(current);
return group;
}
group[index].count += current.count;
return group;
}, []);
对于您的第二级问题,您可能希望将array.prototype.map与reduce配对。
const test = [
{date: "2017-09-28", type: "line", count: 1},
{date: "2017-09-28", type: "line", count: 1},
{date: "2017-09-28", type: "dot", count: 1},
{date: "2017-09-26", type: "dot", count: 1}
];
const mapper = item => ({
date: item.date,
dot_count: (item.type === 'dot') ? 1 : 0,
line_count: (item.type === 'line') ? 1 : 0,
total_count: item.count,
});
const reducer = (group, current) => {
let index = group.findIndex(ele => ele.date === current.date);
if (index === -1) {
group.push(current);
return group;
}
group[index] = {
...group[index],
dot_count: group[index].dot_count + current.dot_count,
line_count: group[index].line_count + current.line_count,
total_count: group[index].total_count + current.total_count,
};
return group;
};
let result = test.map(mapper).reduce(reducer, []);
console.log(result);