0

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?

3
  • "does not give me a list object as a value for a particular state" --- should we guess what it does return instead? Commented Jul 21, 2014 at 9:14
  • I should get a map object which has the key set to state and the value containing the array of objects containing the state. Commented Jul 21, 2014 at 9:15
  • I see what you want to get, but what is wrong with the given code. Did you provide it to us for some particular reason? Commented Jul 21, 2014 at 9:17

1 Answer 1

3

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": [...], ...}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.