R111
R111

Reputation: 171

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

Upvotes: 1

Views: 3338

Answers (2)

You can use something like this

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

_.set(myObj, 'results.results', _.uniqBy(_.get(myObj, 'results.results'), 'id'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

Upvotes: 0

lankovova
lankovova

Reputation: 1426

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>

Upvotes: 1

Related Questions