Search code examples
arrayslodash

Loop and merge object in Lodash


I have a array of object, like this:

var obj = [{
    employeeId: 1300000,
    requestValue: 2
}, {
    employeeId: 1300000,
    requestValue: 3
}, {
    employeeId: 1300001,
    requestValue: 4
}]

I know how to do it in javascript. But, How can I a retrieve the following result using Lodash:

var result = {
    1300000: [
        { requestValue: 2 },
        { requestValue: 3 }
    ],
    1300001: [
        { requestValue: 4 }
    ]
}

Solution

  • Using Lodash:

    1. Group By with employeeId
    2. mapValues to map each group, and take only requestValue by using map

    Here is the example:

    let input = [{"employeeId":1300000,"requestValue":2},{"employeeId":1300000,"requestValue":3},{"employeeId":1300001,"requestValue":4}],
        res = _(input)
                .groupBy('employeeId')
                .mapValues(g => _.map(g, ({requestValue}) => ({requestValue})))
                .value();
                
    console.log(res)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    Using Plain JavaScript

    1. Take a hash (resulant) and start with iterating it using reduce
    2. Check if the employee id exists as a key of the hash for each employeeId, if exist use it otherwise create the key value pair with a empty array
    3. Take either the existing value (for the key) or the new one and push requestValue

    let input = [{"employeeId":1300000,"requestValue":2},{"employeeId":1300000,"requestValue":3},{"employeeId":1300001,"requestValue":4}],
        res = input.reduce((r, {employeeId, requestValue})=> {
    	          (r[employeeId] = r[employeeId] || []).push({requestValue});
    	          return r;
              }, {});
              
    console.log(res);