Parveen Sachdeva
Parveen Sachdeva

Reputation: 1019

GroupBy items Using Underscore based on two keys

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

Answers (3)

Yosvel Quintero
Yosvel Quintero

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

Abslen Char
Abslen Char

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

Mick
Mick

Reputation: 917

var result = _.groupBy(obj, function(o){
    return o.model + o.color;
});

Upvotes: 0

Related Questions