zilcuanu
zilcuanu

Reputation: 3715

How to filter the json data using Underscore

I am new to Underscore. I have a json array which is pasted below. If I want to filter the below array based on developed field having "yes" as value. How can I do using Underscore.js. Currently I am iterating over the content of array and manually selecting the objects and populating in into another array. Is there a better way to do using Underscore?

  {
    "content": [
    {
      "stateName": "Karnataka",
      "population": 1000000,
      "developed": "yes"
    },
    {
      "stateName": "Kerala",
      "population": 1000000,
      "developed": "yes"
    },
    {
      "stateName": "Tamilnadu",
      "population": 1023213213213,
      "developd": "yes"
    },
    {
      "stateName": "Bsadasd",
      "population": 1023213213213,
      "developed": "no"
    }
  ]
}

Upvotes: 2

Views: 1613

Answers (3)

nikoshr
nikoshr

Reputation: 33344

You can filter an array on its properties by using _.where :

where _.where(list, properties)

Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

which leads to

var filtered = _.where(data.content, {developed: "yes"});

and a demo http://jsfiddle.net/nikoshr/NExZC/

Upvotes: 2

Gruff Bunny
Gruff Bunny

Reputation: 27976

Not sure if I'm missing something here but the obvious underscore function is filter:

var developedStates = _.filter(data.content, function(state){
    return state.developed == 'yes';
});

Upvotes: 2

Igor Zinov'yev
Igor Zinov'yev

Reputation: 3706

As far as I know, underscore doesn't have a way to help you with this task. You can do this without using underscore with a native Javascript method called select:

var filteredArray = originalArray.select(function(item, index) {
    return item.developed == "yes"; // Include this item if it has a proper value
}); 

Note that the select method is only available in browsers that support EcmaScript 5 specifications, so for older browsers you will need some supporting library like es5-shim.

Upvotes: 0

Related Questions