Cesar Cabral
Cesar Cabral

Reputation: 341

Manipulation JSON with Lodash

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?

Upvotes: 1

Views: 348

Answers (3)

tokland
tokland

Reputation: 67890

The code included in the question is confusing. Something like this?

const result = _(obj)
  .groupBy("type")
  .mapValues(objs => objs.map(o => o.messages))
  .value()

Upvotes: 1

lellefood
lellefood

Reputation: 2096

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);

Upvotes: 1

CoderPi
CoderPi

Reputation: 13211

Libraries are not always the way to go:

function groupMessagesByType(dataIn) {
  let dataOut = {}
  
  for(var i = 0; i < dataIn.length; ++i) {
    var type = dataIn[i].type
    if(typeof dataOut[type] == "undefined") {
      dataOut[type] = []
    }
    dataOut[type].push(dataIn[i].messages)
  }

  return dataOut
}

// Example:
var data = [{
        "type": "success",
        "messages": "Assignment saved."
    }, {
        "type": "success",
        "messages": "Assignment saved."
    }, {
        "type": "error",
        "messages": "Error msg."
    }]
console.log(groupMessagesByType(data))

Upvotes: 0

Related Questions