Reputation: 59
JavaScript - How to count each key value in 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}
]
with this JSON format to:
[
{date: "2017-09-26", count: 1},
{date: "2017-09-28", count: 3}
]
or
ultimately, to:
[
{date: "2017-09-26", dot_count: 1, line_count: 0},
{date: "2017-09-28", dot_count: 1, line_count: 2}
]
Upvotes: 0
Views: 144
Reputation: 1619
You are probably looking for 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;
}, []);
for your second level question you probably want to pair array.prototype.map with 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);
Upvotes: 0
Reputation: 386540
You could use a hash table and create a new object if the hash does not exists. Later add the count value to the group.
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; }
Upvotes: 2