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

how to create array of object in javascript group by specific field?

I have a data like this:

const input = [ {title: 'head', value: a, amount: 10},
                {title: 'head', value: b, amount: 5},
                {title: 'body', value: c, amount: 20} ];

I want to make an array of object literals with data like this:

const output = [{title: 'head',
                 values: [{value: a, amount: 10},
                          {value: b, amount: 5}]
                },
                {title: 'body',
                 values: [{value: a, amount: 20}]
                }];

since I’m not used to javascript, I’m having trouble wrapping values by title. 🥲

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

plz help me.

>Solution :

You can use Set to get the unique values and then map matching entries to the result like this:

const out = [...new Set(input.map(i=>i.title))].map(e=>{
    return {
        title: e,
        values: input.filter(p=>p.title === e).map(p=>{
            return {
                value: p.value,
                amount: p.amount
            };
        })
    };
});
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