Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get uniq nested object array with lodash

My data had nested objects with array. I want to make the nested object atrribute unique from the output. Currenly I'm using lodash v4 above, I found a solution suitable but only works in lodash v3.

Data

[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
},
{
   menu: { id: 1 },
   other: { data: "another1" }
}]

Expected output

[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
}]

Similar lodash v3 solution is here. What is the solution for v4? Solution without lodash still accepted as long as the codes are running faster and simple.

like image 258
Foonation Avatar asked Aug 01 '26 19:08

Foonation


1 Answers

You can use uniq method as below.

var arr = [{
  menu: {
    id: 1
  }
}, {
  menu: {
    id: 2
  }
}, {
  menu: {
    id: 1
  }
}];

var unique = _.uniq(arr, 'menu.id');
console.log(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>

With lodash 4.x.x, use uniqBy

var arr = [{
  menu: {
    id: 1
  },
  other: {
    data: "another1"
  }
}, {
  menu: {
    id: 2
  },
  other: {
    data: "another2"
  }
}, {
  menu: {
    id: 1
  },
  other: {
    data: "another1"
  }
}];

console.log(_.uniqBy(arr, 'menu.id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 118
Tushar Avatar answered Aug 03 '26 08:08

Tushar