0

I have an issue trying to retrieve a function parameter value as an object property selector into a .filter() method.

This is my code:

myFunction(property, value) {
    function myFilter(obj) {
        return obj.details.name == value;
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(myFilter));
}

I want to replace return obj.details.name == value; by return obj.property == value;.

obj.property is the parameter of my function myFunction(property, value). The value parameter value works fine and is well retrieved.

This is what I want:

getFilteredFMsBy(property, value) {
    function specificFilter(obj) {
        return obj.property == value;
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}

If I define the value of property in the function, same case. It doesn't work:

getFilteredFMsBy(property, value) {
    property = "details.name";
    function specificFilter(obj) {
        return obj.property == value;
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}

Any idea?

Jonathan
  • 375
  • 1
  • 7
  • 18

2 Answers2

1

Seems like you need to access object[prop][prop2] given the object and the string "prop.prop2"

from this answer: Javascript: Get deep value from object by passing path to it as string you can do deepFind:

function deepFind(obj, path) {
  var paths = path.split('.')
    , current = obj
    , i;

  for (i = 0; i < paths.length; ++i) {
    if (current[paths[i]] == undefined) {
      return undefined;
    } else {
      current = current[paths[i]];
    }
  }
  return current;
}

then do

getFilteredFMsBy(property, value) {
    property = "details.name";
    function specificFilter(obj) {
        return deepFind(obj, property) == value; // <-- use it here
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}
Community
  • 1
  • 1
Ahmed Musallam
  • 9,523
  • 4
  • 27
  • 47
0

How about this?

getFilteredFMsBy(property: string, value:any) {
    return this._http.get(this.Url).map((response: Response) => response.json().filter((obj) => { return obj[property] == value; }));
}
wannadream
  • 1,669
  • 1
  • 12
  • 14