user3444463 user3444463 - 1 year ago 176
JSON Question

JavaScript - How to count each key value in JSON?

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}
]

Answer Source

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; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download