Search code examples
javascriptjsonangulartypescriptchart.js

Extract arrays from JSON


I'm trying to extract some data from JSON response (from REST API to angular) into arrays to use in Chartjs. The JSON is in this format

[
    {
        "A": a,
        "B": b,
        "C": c
    },
    {
        "A": aa,
        "B": bb,
        "C": cc
    },
    {
        "A": aaa,
        "B": bbb,
        "C": ccc
    }
] 

I want it into arrays like this

A = [a,aa,aaa]
B = [b,bb,bbb]
C = [c,cc,ccc]

I just started using angular and I searched a lot for a solution. But, I couldn't find one. Any help is appreciated.


Solution

  • It can be achieved this way:

    const obj = {};
    array.forEach((item) => {
        Object.entries(item).forEach(([key, value]) => {
            if(key in obj) {
                obj[key].push(value);
            } else {
                obj[key] = [value];
            }
        });
    });
    console.log(obj);