Glen Pierce
Glen Pierce

Reputation: 4811

Pass JSON key in function

Is it possible to specify the key of an object as a function parameter? For example, if I wanted to create a filter function that could filter several map markers by marker.element.country or marker.element.population?

This way I could write filter("England", country) and filter(100000, population)

var markers = [...some array of JSON objects];
function filter(value, filterBy){
    markers.forEach(function (marker) {
        marker.setVisible(marker.element[filterBy] == value);
        //marker.setVisible(marker.element.filterBy == value); -didn't work either
    });
};

I'm not looking for a work around. I know I could code several separate functions or create some conditional within this function that behaves differently based on the value of filterBy.

This is no fun:

var markers = [...some array of JSON objects];
function filter(value, filterBy){
    if(filterBy == "country"){
        markers.forEach(function (marker) {
            marker.setVisible(marker.element.country == value);
        });
    }
    if(filterBy == "population"){
        markers.forEach(function (marker) {
            marker.setVisible(marker.element.population == value);
        });
    }
};

Upvotes: 1

Views: 53

Answers (1)

quirimmo
quirimmo

Reputation: 9988

Actually you can use the standard array filter function to achieve it:

var markers = [ { country: 'England', population: 1000}, {country: 'Italy', population: 50}];
function customfilter(value, filterBy){
  return markers.filter(function(el) {
  	if(el.hasOwnProperty(filterBy) && el[filterBy] === value) {
      return el;
    }
  });
};
console.log(customfilter('Italy', 'country'));

Upvotes: 1

Related Questions