Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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'
    }
]

I want to show as follows:

  • Shop 1 ProductId: 123 ProductId: 4232 ProductId: 3332
  • Shop 2 ProductId: 457 ProductId: 33221
  • Shop 3 ProductId 452113

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...