merge object & sum a single property javascript

前端 未结 4 1280
南旧
南旧 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:24

    A simple approach:

    Loop over data and create an object where key will be unique id and its value will be quantity. Then loop back over object's keys and create objects.

    var data = [{ item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }, { item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }]
    
    var r = {};
    data.forEach(function(o){
      r[o.item_guid] = (r[o.item_guid] || 0) + o.quantity;
    })
    
    var result = Object.keys(r).map(function(k){
      return { item_guid: k, quantity: r[k] }
    });
    console.log(result)

提交回复
热议问题