Home > OS >  How to group by array of objects
How to group by array of objects

Time:12-24

I have an array of objects like the below:

const data = [{label: 'ABC', id: '1', emp:{empLabel: 'Test1', empId: '12'}},
{label: 'ABC', id: '1', emp:{empLabel: 'Test2', empId: '13'}},
{label: 'DEF', id: '2', emp:{empLabel: 'Test11', empId: '14'}},
{label: 'DEF', id: '2', emp:{empLabel: 'Test12', empId: '15'}},
{label: 'PQR', id: '3', emp:{empLabel: 'Test13', empId: '16'}},
{label: 'XYZ', id: '4', emp:{empLabel: 'Test14', empId: '17'}}
] 

I am trying to club the emp data if my id is equal.

Expected Output:

[
{label: 'ABC', id: '1', emp:[{empLabel: 'Test1', empId: '12'}, {empLabel: 'Test2', empId: '13'}]},
{label: 'DEF', id: '2', emp:[{empLabel: 'Test11', empId: '14'}, {empLabel: 'Test12', empId: '15'}]},
{label: 'PQR', id: '3', emp:{empLabel: 'Test13', empId: '16'}},
{label: 'XYZ', id: '4', emp:{empLabel: 'Test14', empId: '17'}}
] 

I have tried to do this by lodash but am not sure how to proceed after this. Any help would appreciate?

My Approach:

result = _.map(data, eachData => {
  return _.chain(_.flatMap(eachData))
  
  })

CodePudding user response:

const _ = require("lodash")

let items = [
    { label: 'ABC', id: '1', emp: { empLabel: 'Test1', empId: '12' } },
    { label: 'ABC', id: '1', emp: { empLabel: 'Test2', empId: '13' } },
    { label: 'DEF', id: '2', emp: { empLabel: 'Test11', empId: '14' } },
    { label: 'DEF', id: '2', emp: { empLabel: 'Test12', empId: '15' } },
    { label: 'PQR', id: '3', emp: { empLabel: 'Test13', empId: '16' } },
    { label: 'XYZ', id: '4', emp: { empLabel: 'Test14', empId: '17' } }
]


var result = _(items)
    .groupBy('id')
    .map(function(items, label) {
      return {
        label: label,
        emp: _.map(items, 'emp')
      };
    }).value();
console.log("result -> ", result)

CodePudding user response:

This works, unless you are specifically trying to use lodash:

const result = data.reduce((acc, val) => {
    const existingGroup = acc.find((group) => val.id === group.id);

    if(!!existingGroup) {
        if(existingGroup.emp && Array.isArray(existingGroup.emp)) {
           existingGroup.emp = [...existingGroup.emp, val.emp];
        } else {
          existingGroup.emp = [existingGroup.emp, val.emp]
        }
    } else {
        acc = [...acc, val];
    }
    return acc;
},[]);

console.log(result);

CodePudding user response:

Try using array.filter(). Do something like

ar = []
let newarr = []
data.map(x => if (ar.indexOf(x)===-1) {newarr.push(x); at.push(x.id))

newArr is now your array.

  • Related