1

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. 🥲

plz help me.

3
  • I found this thread which is related to your question: stackoverflow.com/questions/40774697/… Commented Jul 29, 2022 at 10:17
  • Does this answer your question? How can I group an array of objects by key? Commented Jul 29, 2022 at 10:19
  • I already see those answers, but I need to describe key 'title' instead of using value as a key. but thanks for the links! Commented Jul 29, 2022 at 10:24

1 Answer 1

3

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
            };
        })
    };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.