0

I have an array of objects. The constructor is

Planet : function(planet)
{
    this.name = planet.name;
    this.percComp = planet.percComp;
    this.preReq = planet.preReq;
}

Is there a way using jquery or underscore to get an object or objects, out of the array based on the objects parameter.

Something like

_getItem(planetArray, Planet.name === 'Mars')

3 Answers 3

2

try Underscore's where method

_.where(listOfPlanets, {name: "Mars"});

Say you have the following list of planets - prop is a made up property

var listOfPlanets = [
    { name: 'Mercury', prop:1},
    { name: 'Venus', prop:2},
    { name: 'Earth', prop:3},
    { name: 'Mars', prop:4},
    { name: 'Jupiter', prop:5},
    { name: 'Saturn', prop:6},
    { name: 'Uranus', prop:7},
    { name: 'Neptune', prop:8} ];

To get the Mars object just do the following. Keep in mind that _.where returns an array of matches. Accessing the index 0 or using _.first will be needed

var mars = _.where(listOfPlanets, {name: "Mars"})[0];
console.log(mars.prop);    // 4

Underscore also has a _.find method, which can be used to retrieve only the first match

var mars = _.find(listOfPlanets, function(p){ return p.name === 'Mars' });
console.log(mars.prop);    // 4

JSFiddle here: http://jsfiddle.net/jaimem/6bxnK/1/

Sign up to request clarification or add additional context in comments.

Comments

2

This is what jQuery's grep method is for:

var theObject = $.grep(planetArray, function (el) {
    return el.name === 'mars';
})[0];

Here's the fiddle: http://jsfiddle.net/g7syV/

Comments

1

You can use grep:

 $.grep(arr, function (obj) { return obj.name === 'Mars'; });

This will return an array of objects that meet the criteria.

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.