Reputation: 1019
I've one object, which I want to be group by based on two keys.
var obj = [{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red1"
}];
var result = _.groupBy(obj, p=>p.model);
gives me one result.
I want this to be group Base on model and color, so that I've two results as:
result = [{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red"
}];
How I can do this with the help of Underscore js or any other short way.
Upvotes: 1
Views: 88
Reputation: 19070
With underscore.js groupBy you can group multiple properties like this:
const obj = [{make: "nissan",model: "sunny",colour: "red"}, {make: "nissan",model: "sunny",colour: "red"},{make: "nissan",model: "sunny",colour: "red1"}];
const result = _.groupBy(obj, item => item.model + '#' + item.colour);
console.log(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
But the result
you show in your question looks like you need is Array.prototype.filter():
const obj = [{make: "nissan",model: "sunny",colour: "red"}, {make: "nissan",model: "sunny",colour: "red"},{make: "nissan",model: "sunny",colour: "red1"}];
const result = obj.filter(item => item.model === 'sunny' && item.colour === 'red');
console.log(result);
Upvotes: 3
Reputation: 3135
since you asked "How I can do this with the help of Underscore js or any other short way" , here is a short way using Array.prototype.filter()
var obj = [{
make: "nissan",
model: "sunny",
colour: "red"
},{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red1"
}];
var res = obj.filter( key => key.colour === "red")
console.log(res)
Upvotes: 1
Reputation: 917
var result = _.groupBy(obj, function(o){
return o.model + o.color;
});
Upvotes: 0