Search code examples
javascriptlodash

How to use javascript lodash uniqBy on a nested attribute


I have an object that is structured similar as follows (simplified version):

{
   "time": 100,
   "complete" : true,
   "results" : {
       "total": 10,
       "score": 3,
       "results": [ 
           {
           "id" : 123,
           "name": "test123"
            },
            {
           "id" : 123,
           "name": "test4554"
            }
          ]
       }     
 }

How do I use lodash ._uniqBy to deduplicate the results, based on results.results.id being the unique key?

To clarify, I would like the deduplicated resultset to be returned within the original object structure, e.g.

 {
   "time": 100,
   "complete" : true,
   "results" : {
       "total": 10,
       "score": 3,
       "results": [ 
           {
           "id" : 123,
           "name": "test123"
            }
          ]
       }     
 }

thanks


Solution

  • You can achieve your goal by simply passing the right part of your object into _.uniqBy(array, [iteratee=_.identity]) function.

    Next thing you want to do is to 'concat' lodash uniqBy result and your object. This is a little bit tricky. I suggest you to use ES6 Object.assign() method and spread operator.

    Check out my solution. Hope this helps.

    const myObj = {
      "time": 100,
      "complete" : true,
      "results" : {
        "total": 10,
        "score": 3,
        "results": [
          {"id" : 123, "name": "test123"},
          {"id" : 123, "name": "test4554"}
        ]
      }     
    };
    
    const uniq = _.uniqBy(myObj.results.results, 'id');
    const resultWrapper = Object.assign({}, myObj.results, { results: [...uniq] });
    const resultObj = Object.assign({}, myObj, { results: resultWrapper });
    
    console.log( resultObj );
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>