merge object & sum a single property javascript

前端 未结 4 1282
南旧
南旧 2021-01-18 13:28

i have an array like this

[
  {
    item_guid: \"57e7a1cd6a3f3669dc03db58\"
    quantity:3
  },
  {
    item_guid: \"57e77b06e0566d496b51fed5\"
    quantity:         


        
4条回答
  •  天涯浪人
    2021-01-18 14:05

    You can

    • group your objects by item_guid
    • sum the objects in the resulting groups
    • transform these groups in the format you want

    Something like this:

    var result = _.chain(data)
        .groupBy('item_guid')
        .map(function(objects, guid) {
            return {
                item_guid: guid, 
                quantity: _.sumBy(objects, 'quantity')
            };
        })
        .value();
    

    And a demo

    var data = [
      {
        item_guid: "57e7a1cd6a3f3669dc03db58",
        quantity:3
      },
      {
        item_guid: "57e77b06e0566d496b51fed5",
        quantity:3
      },
      {
        item_guid: "57e7a1cd6a3f3669dc03db58",
        quantity:3
       },
      {
        item_guid: "57e77b06e0566d496b51fed5",
        quantity:3
      }
    ];
    
    
    var result = _.chain(data)
        .groupBy('item_guid')
        .map(function(objects, guid) {
            return {
                item_guid: guid, 
                quantity: _.sumBy(objects, 'quantity')
            };
        })
        .value();
      
      console.log(result);

提交回复
热议问题