GroupBy项目使用基于两个键的下划线

时间:2018-03-26 12:25:30

标签: javascript underscore.js

我有一个对象,我希望根据两个键进行分组。

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);

给了我一个结果。

我希望这是基于模型和颜色的组,所以我有两个结果:

result =  [{
  make: "nissan",
  model: "sunny",
  colour: "red"
},
{
  make: "nissan",
  model: "sunny",
  colour: "red"
}];

如何借助Underscore js或任何其他简短的方法来做到这一点。

3 个答案:

答案 0 :(得分:3)

使用underscore.js groupBy,您可以对多个属性进行分组:

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>

但您在问题中显示的result似乎是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);

答案 1 :(得分:1)

因为你问过&#34; 如何在Underscore js或任何其他简短方法的帮助下做到这一点&#34; ,这是使用Array.prototype.filter()

的简短方法

&#13;
&#13;
 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)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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