Answers for "javascript for group object properties based on another property"

0

javascript for group object properties based on another property

var list = [
     {   date: "2017-01-01",
         type: "type1",
         amount: 100
     },
     {   date: "2017-01-01",
         type: "type2",
         amount: 150
     },
     {   date: "2017-01-02",
         type: "type1",
         amount: 200
     }]

var dateArrKeyHolder = [];
var dateArr = [];
list.forEach(function(item){
    dateArrKeyHolder[item.date] = dateArrKeyHolder[item.date]||{};
    var obj = dateArrKeyHolder[item.date];
    if(Object.keys(obj).length == 0)
    dateArr.push(obj);
    
    obj.date = item.date;
    obj.activities  = obj.activities || [];
    
    obj.activities.push({type:item.type, amount: item.amount });
});


console.log(JSON.stringify(dateArr));

/* Result:
 [{"date":"2017-01-01","activities":[{"type":"type1","amount":100},{"type":"type2","amount":150}]},
  {"date":"2017-01-02","activities":[{"type":"type1","amount":200}]}] 
*/
Posted by: Guest on July-01-2020

Code answers related to "javascript for group object properties based on another property"

Code answers related to "Javascript"

Browse Popular Code Answers by Language