Sort and merge JSON keys with matching values

后端 未结 3 1080
一个人的身影
一个人的身影 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 13:56

    This is easily handled by creating a custom object that has properties named with your unique combinations (i.e. type + first 7 of date).

    Loop through your array and check if your "holder" object has an existing property named with your unique identifier. If it has the property already, then increment the quantity, otherwise add a new item.

    After the holder is completely built, clear your array, then loop through the properties of the holder and push them back on to your array.

    var holder = {};
    var json = [
      {
        type: "big",
        date: "2012-12-08",
        qty: 6
      },
      {
        type: "small",
        date: "2012-12-08",
        qty: 9
      },
      {
        type: "big",
        date: "2012-12-15",
        qty: 4
      },
      {
        type: "small",
        date: "2012-12-07",
        qty: 7
      },
      {
        type: "small",
        date: "2012-11-07",
        qty: 3
      }
    ];
    
    json.forEach(function(element) {
      var identifier = element.type + element.date.slice(0, 7);
      if (holder[identifier]) {
        holder[identifier].qty += element.qty;
      } else {
        holder[identifier] = element;
      };
    });
    
    json = [];
    for(var identifier in holder) {
      json.push(holder[identifier]);
    }
    
    console.log(json);

提交回复
热议问题