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?

2

2 Answers 2

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"
   ]
}
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};
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.