groupBy具有underscore.js的对象数组

时间:2016-11-10 13:28:20

标签: javascript jquery underscore.js

我有一个对象阵列(订单)(产品):我希望按ID分组和计算所有这些产品:

var order = [
{ product_id: 70, product_price: 9, product_color: "ccc"},
{ product_id: 70, product_price: 9, product_color: "ccc"},
{ product_id: 71, product_price: 10, product_color: "fff" } ];

使用Underscore.js:

var groups = _.countBy(order, function(value){
    return value.product_id + "#" + value.product_price + "#" + value.product_color;
})
//--> Object {70#ccc#9: 2, 71#fff#10: 1}

所以它有效...但是现在,我怎么能将这些值返回到这样的数组中,所以我可以将它作为一个新的对象数组来处理?

 [
    { product_id: 70, product_price: 9, product_color: "ccc", count: 2},
    { product_id: 70, product_price: 9, product_color: "fff", count: 1}
 ];

2 个答案:

答案 0 :(得分:1)

您可以在组中使用groupBy然后map来代替countBy来添加计数:

var groups = _.groupBy(order, function(value){
    return value.product_id + "#" + value.product_price + "#" + value.product_color;
})

groups = _.map(groups, function(group){
    return _.extend(group[0], {count: group.length});
});

答案 1 :(得分:0)

您可以使用reduce来重新创建原始数组。

var countedById = [
    { product_id: 70, product_price: 9, product_color: "ccc", count: 2},
    { product_id: 70, product_price: 9, product_color: "fff", count: 1}
 ];

var original = countedById.reduce((acc, cur) => {
  for (var i = 0; i < cur.count; i++) {
    var original = {
      product_id: cur.product_id,
      product_price: cur.product_price,
      product_color: cur.product_color
    }
    acc.push(original);
  }
  return acc;
  }, []);

document.write(JSON.stringify(original))