groupBy计入lodash

时间:2016-08-10 09:06:31

标签: javascript arrays lodash

我有一个像这样的对象数组:

[
  {
    rating: 1
  },
  {
    rating: 2
  },
  {
    rating: 3
  },
  {
    rating: 1
  }
]

我想要这样的结果 -

{
  1: 2,
  2: 1,
  3: 1
}

它将是Rating_Value: Count

我怎么能在lodash中这样做?或者如果没有lodash可以优化它?

3 个答案:

答案 0 :(得分:9)

您可以使用lodash#countBy

var result = _.countBy(data, 'rating');



var data = [
  {
    rating: 1
  },
  {
    rating: 2
  },
  {
    rating: 3
  },
  {
    rating: 1
  }
];

var result = _.countBy(data, 'rating');

console.log(result);

<script src="https://cdn.jsdelivr.net/lodash/4.14.2/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用reduce()来获得此结果。

&#13;
&#13;
var data = [{"rating":1},{"rating":2},{"rating":3},{"rating":1}];

var result = data.reduce(function(r, e) {
  r[e.rating] = (r[e.rating] || 0) + 1;
  return r;
}, {});

console.log(result)
&#13;
&#13;
&#13;

答案 2 :(得分:1)

你可以在纯JS中这样做:

var myArr = [
  {
    rating: 1
  },
  {
    rating: 2
  },
  {
    rating: 3
  },
  {
    rating: 1
  }
];

var ratingObject = {};

myArr.forEach(function(valueObject) {
   ratingObject[valueObject.rating] = ratingObject[valueObject.rating] ? ratingObject[valueObject.rating] + 1 : 1;
});