1

I want to group array of objects by its key,

The Original form;

data = [
    {'id': 1, 'name': 'karthik'},
    {'id': 1, 'age': 31},
    {'id': 2, 'name': 'ramesh'},
    {'id': 2,  'age': 22}
];

To transform in to,

groupedData = [
    {'id': 1, 'name': 'karthik', 'age': 31},
    {'id': 2, 'name': 'ramesh', 'age': 22}
];

What I tried,

this.data.map(item => item.id)
        .filter((item, index, all) => all.indexOf(item) === index);
        console.log(this.data);

4 Answers 4

3

Use reduce instead of map.

const groupedData = Object.values(this.data.reduce((a, { id, ...r }) => ({ ...a, [id]: { ...(a[id] || { id }), ...r }}), {}));

How this works:

Firstly, using reduce is far easier than any map solution because it allows us to have an accumulator value a.

Then, we extract the id, and the rest of the properties (because we don't know what they're called).

We return a, with the property keyed with the value of id being either the existing property or a new one with id, as well as the rest of the properties.

Sign up to request clarification or add additional context in comments.

3 Comments

please explain what is it doin?
Edited @kartik, does that help?
No problem @ChrisY, always glad to help. Here's some reading material on reduce to help you understand how the code works a little better.
1

You can use reduce to create an object ( a table ) for each id.

const groupMap = data.reduce((group, currentData) => {
    const id = currentData['id']
    group[id] = { ...(group[id] || {}), ...currentData }
    return group
} ,{})

what this returns is something like:

{
  "1": {
    "id": 1,
    "name": "karthik",
    "age": 31
  },
  "2": {
    "id": 2,
    "name": "ramesh",
    "age": 22
  }
}

group[id] = { ...(group[id] || {}), ...currentData } is basically "if you already saw this id, just merge the previous data with the current data"

then you can get the final result calling Object.values

const groupedData = Object.values(groupMap)

which just get the values of the object created above.

2 Comments

you can copy and paste in your browser's console, and see all the steps.
please explain what is it doin?
0

Try this

data = data.reduce((total, current, index) => {
for(let key in current) total[index][key] = current[key]
return total
}, [])

Comments

0

This function will help you)

    function mergeobj(arrofobj) {
 arrofobj.map((item, index) => {
    for (let i = 0; i < arrofobj.length; i++) {
        if(i==index)continue;
        if (item['id'] == arrofobj[i]['id']) {
            item = Object.assign(item, arrofobj[i]);
            arrofobj.splice(i, 1);
            --i;
        }
    }
    return item;
})
return arrofobj; }

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.