using this code let result = _.groupBy(obj, 'type');
I have this return:
{
"success": [{
"type": "success",
"messages": "Assignment saved."
}, {
"type": "success",
"messages": "Assignment saved."
}, {
"type": "success",
"messages": "Assignment saved."
}]
}
But I need to convert to this:
{
"error": ["Error msg", "Error 2 msg", "Error 3 msg"],
"notice": ["Notice 1 msg", "Notice 2 msg"],
"success": ["Success 1 msg", "Success 2 msg", "Success 3 msg"]
}
What should I do differently in my code?
Some configuration on Lodash that I'm missing?
Take a look to this fiddle for a working solution. With this solution you are not locked to the same 3 type of message.
Ive used _.groupBy
let list = [{type: "success", message: "msg1"},{type: "success", message: "msg2"},{type: "success", message: "msg3"},{type: "notice", message: "msg1"}, {type: "notice", message: "msg2"}, {type: "error", message: "msg1"}]
console.log("\n\n---------Full initial list of events");
console.log(list);
console.log("\n\n---------Events grouped by type");
console.log(_.groupBy(list, 'type'));
console.log("\n\n---------Your format");
let groups = _.groupBy(list, 'type')
let keys = Object.keys(groups);
for (let key of keys) {
groups[key] = groups[key].map(elem => elem.message)
}
console.log(groups);