Reputation: 153
I have an object like this
data: [
{
"Type":"100, S4",
"Model":"1 serie, e82",
"Manufacturer":"BMW",
"Vehicle":"Cars"
},
{
"Type":"type 2",
"Model":"a serie",
"Manufacturer":"Toyota",
"Vehicle":"Cars"
},
{
"Type":"type 3",
"Model":"v4",
"Manufacturer":"Toyota",
"Vehicle":"SUVs"
}
]
then I used jquery and lodash library with expect to return distinct value from the object.
Tried #1:
$.each( data, function( i, value ) {
var vehicles = _.uniqBy(value);
console.log(vehicles);
});
Result: got 3 empty arrays printed in console.log
Tried #2:
$.each( data, function( i, value ) {
var vehicles = _.uniqBy(value.Vehicle);
console.log(vehicles);
});
Result: 4 arrays within split characters
(4) ["C", "a", "r", "s"]
(4) ["C", "a", "r", "s"]
(4) ["S", "U", "V", "s"]
I expected to got an array within
["Cars", "SUVs"]
How could I deal with it? Thanks for help!
Upvotes: 0
Views: 952
Reputation: 30088
You can use lodash#map
to get all Vehicle
property strings, and then use lodash#uniq
to remove all duplicate strings.
var result = _(data).map('Vehicle').uniq().value();
var data = [
{
"Type":"100, S4",
"Model":"1 serie, e82",
"Manufacturer":"BMW",
"Vehicle":"Cars"
},
{
"Type":"type 2",
"Model":"a serie",
"Manufacturer":"Toyota",
"Vehicle":"Cars"
},
{
"Type":"type 3",
"Model":"v4",
"Manufacturer":"Toyota",
"Vehicle":"SUVs"
}
];
var result = _(data).map('Vehicle').uniq().value();
console.log(result);
body > div { top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Upvotes: 1
Reputation: 619
Try this
var vehicles = _.uniqBy(data, function (e) {
return e.Vehicle;
}).map(function(veh){
return veh.Vehicle;
});
console.log(vehicles);
Upvotes: 1