Asdfg
Asdfg

Reputation: 12213

writing generic filter using grep in jQuery

Is there a way i can write the following piece of code to be more generic?

var result = $.grep(myObjectArray, function(e){ 

    return e.Prop1 == 'SomeVal';

});

This is what i want to do.

A generic function that will accept myObjectArray (Object Array to filter), Prop1(Property name) and SomeVal (Value to filter) as an argument.

The problem i am facing is that i dont know how will i find the PropertyName in the object as it can be anything.

Any help will be highly appreciated.

Upvotes: 0

Views: 251

Answers (3)

Ahamed Mustafa M
Ahamed Mustafa M

Reputation: 3139

Can it be generic like this?

function filterArray(inputArray,customFunction){
 return $.grep(inputArray, function(e){       return customFunction(e);  });
}

where customFunction can be a user defined function to qualify the object as selected

Example :

var sampleArray = [{name:"Ahamed",age: 21}, 
                   {name:"AhamedX",age: 21}, 
                   {name:"Babu",age: 25}, 
                  {name:"Mustafa",age: 27} ];

function nameComparator(obj){
       return obj["name"]=="Ahamed";
}

function ageFilter(obj){
    return obj["age"]>=25;
 }


var filteredArray=filterArray(sampleArray,nameComparator);
alert(filteredArray.length);
var filteredArray=filterArray(sampleArray,ageFilter);
alert(filteredArray.length);

Fiddle link : http://jsfiddle.net/MAq6c/

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

function filterObjectArray(myObjectArray, prop1, someVal) {
    return $.grep(myObjectArray, function (e) {
        return e[prop1] === someVal;
    };
}

Note the use of the square bracket syntax for object property access.

Upvotes: 1

izb
izb

Reputation: 51771

To get the property from an object, just use

myObject[Prop1]

To determine whether an object has a property, use

myObject.hasOwnProperty(Prop1)

Upvotes: 1

Related Questions