1

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))
  
  })
1

3 Answers 3

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

Comments

1

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);

Comments

1

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.

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.