I want to use the _.where underscore function but I can’t seem do get it to work on an array of objects. I have the following json:
var Planets = [
{name:"maths", percComp: "2", preReq: "english"},
{name:"english", percComp: "20", preReq: "geog"},
{name:"german", percComp: "20", preReq: "english"},
{name:"history", percComp: "20", preReq: "german"},
{name:"irish", percComp: "20", preReq: "geog"},
{name:"geog", percComp: "20", preReq: ""},
{name:"french", percComp: "20", preReq: "spanish"},
{name:"spanish", percComp: "57", preReq: "french"}
];
And then I am using the following code to add each to an array:
$(jQuery.parseJSON(JSON.stringify(Planets))).each(function(){
var planet = new Class.Planet(this, paper);
universe.push(planet);
});
I am trying to use underscore to get items from the list as follows:
var planets = _.where(universe, {name: "maths"});
But I am getting the following script error:
Uncaught TypeError: Object function (a){return new j(a)} has no method 'where'
EDIT
You could also use something like
var planets = _.filter(Planets, function(p){ return p.name === "maths"});
_.whereis only available in 1.4.0 http://underscorejs.org/#whereYou have to use Varon’s suggestion with
_.findOr you can simply use JS https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
Example: http://jsfiddle.net/4mxjb/2/