0

I have a JSON object like so:

{  
   "Sat Jul 28 2018 03:36:36 GMT-0700 (Pacific Daylight Time)":[  
      { ... },
      { ... }
   ],
   "Fri Aug 03 2018 19:07:14 GMT-0700 (Pacific Daylight Time)":[  
      { ... }
   ],
   "Sat Aug 18 2018 17:25:50 GMT-0700 (Pacific Daylight Time)":[  
      { ... }
   ]
}

How can I return this into a grouped object by month?

farhan
  • 335
  • 2
  • 13
  • 1
    seems similar to https://stackoverflow.com/questions/20630676/how-to-group-objects-with-timestamps-properties-by-day-week-month look at the answer of Matt Fletcher – Claudiu Matei Sep 15 '18 at 20:51
  • Possible duplicate of [How to group objects with timestamps properties by day, week, month?](https://stackoverflow.com/questions/20630676/how-to-group-objects-with-timestamps-properties-by-day-week-month) – Dean Coakley Sep 15 '18 at 20:53

2 Answers2

0

Try this (with lodash):

var input = {
  "Sat Jul 28 2018 03:36:36 GMT-0700 (Pacific Daylight Time)": [
    "test", "tester"
  ],
  "Fri Aug 03 2018 19:07:14 GMT-0700 (Pacific Daylight Time)": [
    "tester1"
  ],
  "Sat Aug 18 2018 17:25:50 GMT-0700 (Pacific Daylight Time)": [
    "tester2"
  ]
}
var groupedKeys = _.groupBy(Object.keys(input), function(key) {
  return key.substring(4, 7)
});
var groupedEntries = _.map(groupedKeys, (values, key) => {
  values = _.map(values, (value) => {
    return input[value]
  });
  return {
    key: key,
    values: _.flattenDeep(values)
  };
});
var result = _.reduce(groupedEntries, (result, obj) => {
  result[obj.key] = obj.values;
  return result;
}, {})
console.log(result);

Output:

{
   "Jul": [
      "test",
      "tester"
   ],
   "Aug": [
      "tester1",
      "tester2"
   ]
}
ImGroot
  • 796
  • 1
  • 6
  • 17
0

Loop through the object then extract month and create new object:

let jsonObj = {  
   "Sat Jul 28 2018 03:36:36 GMT-0700 (Pacific Daylight Time)":[{},{}],
   "Fri Aug 03 2018 19:07:14 GMT-0700 (Pacific Daylight Time)":[{}],
   "Sat Aug 18 2018 17:25:50 GMT-0700 (Pacific Daylight Time)":[{}]
};
let grouped = Object.keys(jsonObj).reduce((prev,key,i,all)=>{
    let monthArr = {};
    if(typeof prev === 'string'){
        monthArr[prev.substr(4,3)] = jsonObj[prev];
        prev = {};
    }
    monthArr[key.substr(4,3)] = jsonObj[key];
    return {...prev,...monthArr};
});
Aboalnaga
  • 602
  • 6
  • 16