javascript按数组分组 [英] javascript group by in array

查看:84
本文介绍了javascript按数组分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我拥有的数组进行分组。例如:

I want to group an array that I have. For example:

var shoppingCart = [
    {
        productId: '123',
        price: 12,99
        quantity: 1,
        shopId: 'abc',
        shopName: 'shop 1'
    },
    {
        productId: '457',
        price: 83,33
        quantity: 2,
        shopId: 'asw',
        shopName: 'shop 2'
    },
    {
        productId: '4232',
        price: 47,21
        quantity: 1,
        shopId: 'abc',
        shopName: 'shop 1'
    },
    {
        productId: '3332',
        price: 9,99
        quantity: 4,
        shopId: 'abc',
        shopName: 'shop 1'
    },
    {
        productId: '33221',
        price: 99,21
        quantity: 1,
        shopId: 'asw',
        shopName: 'shop 2'
    },
    {
        productId: '452113',
        price: 22,45
        quantity: 2,
        shopId: 'asdj',
        shopName: 'shop 3'
    }
]

我想显示如下:


  • 商店1
    产品编号:123
    产品编号:4232
    ProductId:3332

  • 商店2
    ProductId:457
    ProductId:33221

  • 商店3
    ProductId 452113

我该怎么做?这个想法是,将为每个商店创建单独的订单。

How can I do that? The idea is that there will be created seperate orders for every store.

推荐答案

使用减少为每个唯一的商店名称创建一个带有键的对象。沿过程将项目推入这些数组:

Use reduce to create an object with a key for each unique shop name. Push items to these arrays as you go along:

// Group objects in an array by a property
var mapBy = function(arr, groupName, propName) {
  return arr.reduce(function(result, item) {
    result[item[groupName]] = result[item[groupName]] || [];
    result[item[groupName]].push(item[propName]);
    return result;
  }, {});
};

var shoppingCart=[{productId:"123",price:12.99,quantity:1,shopId:"abc",shopName:"shop 1"},{productId:"457",price:83.33,quantity:2,shopId:"asw",shopName:"shop 2"},{productId:"4232",price:47.21,quantity:1,shopId:"abc",shopName:"shop 1"},{productId:"3332",price:9.99,quantity:4,shopId:"abc",shopName:"shop 1"},{productId:"33221",price:99.21,quantity:1,shopId:"asw",shopName:"shop 2"},{productId:"452113",price:22.45,quantity:2,shopId:"asdj",shopName:"shop 3"}];

console.log(mapBy(shoppingCart, "shopName", "productId"));

这篇关于javascript按数组分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆