zilcuanu
zilcuanu

Reputation: 3715

Parsing the json array to map using Underscore.js

I am having a json array which I want to parse it to a map object. The key should be the state and the value should be an array objects which has the same state. The sample json is given below:

{
  "totalRec": 10,
  "content": [
    {
      "name": "Pradeep",
      "age": "24",
      "state": "KA"
    },
    {
      "name": "Praveen",
      "age": "30",
      "state": "KA"
    },
    {
      "name": "Navnish",
      "age": "32",
      "state": "GOA"
    },
    {
      "name": "Vinod",
      "age": "32",
      "state": "MH"
    },
    {
      "name": "Vikas",
      "age": "32",
      "state": "MH"
    },
    {
      "name": "Harry",
      "age": "44",
      "state": "MP"
    },
    {
      "name": "Linda",
      "age": "22",
      "state": "GOA"
    },
    {
      "name": "June",
      "age": "18",
      "state": "KA"
    },
    {
      "name": "Sachin",
      "age": "32",
      "state": "GOA"
    },
    {
      "name": "Arjun",
      "age": "30",
      "state": "UP"
    }
  ]
}

I tried using Underscore.js and used the following code:

  var some_map = _.object(_.map(data.content, function(item) {
            return [item.state, item]
        }));

But the above code does not give me a list object as a value for a particular state. I want the value to hold all the objects which contain the state as key.

Can you please let me know where I am going wrong?

Upvotes: 0

Views: 2428

Answers (1)

AKX
AKX

Reputation: 168913

Looks like you're looking for _.groupBy().

Simply

var byState = _.groupBy(data.content, "state");

should get you an object of the form

{"GOA": [{"name": "Sachin", ...}, ...}, "UP": [...], ...}

Upvotes: 3

Related Questions