0

I'm trying to filter down an array of objects. But the property of the object to filter on is defined elsewhere as a variable and not 100% how i can construct the dot-notation syntax.

So i have a array object like this

var listings = [
    {"id" : "1", "name":"a name", "surname" : "a surname"},
    {"id" : "2", "name":"b name", "surname" : "b surname"},
    {"id" : "3", "name":"c name", "surname" : "c surname"}
]

I have a variable the specifies what property of the object to filter on. This variable isn't always set to name. In the example above it could be on id,name or surname.

var filter = 'id'

A var for the filter val to look for

var filterVal = '2'

Then i have this grep call.

listings = $.grep(listings, function (obj, index) {
return  obj.id === filterVal;
});

But instead of having obj.id hard coded I want something like:

obj."value of filter variable" === filterVal

Thanks in advance

Ben

1 Answer 1

9

You can make use of square bracket notation instead of dot notation.

var idKey = "name";
$.grep(listings, function (obj) {
    return obj[idKey] === filterVal;
});
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.