Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group object key values to a new object with same structure (javascript)

could you help me? I have this JSON and I need to group in a new object by key:

[
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
]

Expected Final Result:

    {
        "product": ["name 1","name 2","name 3"],
        "price": ["3000","1000","5000"],
        "inspection": [false,true,false]
    }

I tried to use -> for, foreach <- but not getting a good/optimum result… would you mind helping me, please? (was thinking about reduce, but I didn’t make it work)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

let data = [
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
];

let output = Object.fromEntries(
  Object.keys(data[0]).map(k => 
    [k, data.map(d => d[k])]
  )
);

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading