且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript按数组分组

更新时间:2022-02-20 00:25:13

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

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