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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With