Sort and merge JSON keys with matching values

后端 未结 3 1083
一个人的身影
一个人的身影 2021-01-23 13:19

My JSON looks like this:

json = [
  {
    type: \"big\"
    date: \"2012-12-08\"
    qty: 6
  }
  {
    type: \"small\"
    date: \"2012-12-08\"
    qty: 9
  }
          


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-23 14:06

    Alternative solution:

    var result = [];
    
    $(json).each(function (i, e){
        var search = $.grep(result, function(elm){ return e.type == elm.type && e.date.substring(0, 7) == elm.date; });
        if(search.length == 0)
            result.push({ type: e.type, date: e.date.substring(0, 7), qty: e.qty });
        else
            search[0].qty += e.qty;
    });
    

提交回复
热议问题