Reputation: 215
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.
Upvotes: 7
Views: 6059
Reputation: 22490
Without lodash
.using Array#reduce
var a =[{
menu: { id: 1 },
other: { data: "another1" }
},
{
menu: { id: 2 },
other: { data: "another2" }
},
{
menu: { id: 1 },
other: { data: "another1" }
}]
var res =[];
var fin =a.reduce((a,b)=> {
if(!res.includes(b.menu.id)){
res.push(b.menu.id)
a.push(b)
}
return a;
},[])
console.log(fin)
Upvotes: 1
Reputation: 87203
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>
Upvotes: 7
Reputation: 6564
maybe
_.uniqBy(yourarray, e=>e.menu.id)
var data = [{
menu: { id: 1 },
other: { data: "another1" }
},
{
menu: { id: 2 },
other: { data: "another2" }
},
{
menu: { id: 1 },
other: { data: "another1" }
}]
console.log(_.uniqBy(data, e=>e.menu.id));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
Upvotes: 0