javascript for group object properties based on another property

Solutions on MaxInterview for javascript for group object properties based on another property by the best coders in the world

showing results for - "javascript for group object properties based on another property"
Lennart
30 Jun 2019
1var list = [
2     {   date: "2017-01-01",
3         type: "type1",
4         amount: 100
5     },
6     {   date: "2017-01-01",
7         type: "type2",
8         amount: 150
9     },
10     {   date: "2017-01-02",
11         type: "type1",
12         amount: 200
13     }]
14
15var dateArrKeyHolder = [];
16var dateArr = [];
17list.forEach(function(item){
18    dateArrKeyHolder[item.date] = dateArrKeyHolder[item.date]||{};
19    var obj = dateArrKeyHolder[item.date];
20    if(Object.keys(obj).length == 0)
21    dateArr.push(obj);
22    
23    obj.date = item.date;
24    obj.activities  = obj.activities || [];
25    
26    obj.activities.push({type:item.type, amount: item.amount });
27});
28
29
30console.log(JSON.stringify(dateArr));
31
32/* Result:
33 [{"date":"2017-01-01","activities":[{"type":"type1","amount":100},{"type":"type2","amount":150}]},
34  {"date":"2017-01-02","activities":[{"type":"type1","amount":200}]}] 
35*/