1

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

2
  • 3
    please add the wanted result and what you have tried. Commented Mar 26, 2018 at 17:06
  • done, see above Commented Mar 27, 2018 at 11:46

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your suggested fix. Is it possible to return the deduplicated resultset, within the original object structure? e.g. : { "time": 100, "complete" : true, "results" : { "total": 10, "score": 3, "results": [{ "id" : 123, "name": "test123" }] } };
0

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>

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.