0

I am working on a function for an Angular Pipe and one of the arguments needs to be a string from the template *ngFor="let row of tableRows | filter: searchText : keyName" and then use that to itterate the object in the pipe's function

in component: let keyName = 'name.value'

pipe:

transform(items: any[], searchText: string, keyName: string = ''): any[] {
    if (!items) {
    return [];
    }
    if (!searchText) {
    return items;
    }
    searchText = searchText.toLowerCase();
    console.log(keyName);
    return items.filter( it => {
    return it.keyName.toLowerCase().includes(searchText); //THIS HERE NEEDS TO MATCH THE STRING PROVIDED
    });
}

so lets say the argument string name.value is passed into the function, it.keyName.toLowerCase() needs to get interpreted as it.name.value.toLowerCase()

2
  • return it[keyName.toLowerCase()].includes(searchText); ? Commented Jan 19, 2018 at 14:21
  • that didn't work Commented Jan 19, 2018 at 14:25

1 Answer 1

2

You can use the property accessor bracket notation (e.g. object[property]) to access the nested property.

For instance try the deepAccessUsingString function described here: https://medium.com/@chekofif/using-es6-s-proxy-for-safe-object-property-access-f42fa4380b2c

function deepAccessUsingString(obj, key){
  return key.split('.').reduce((nestedObject, key) => {
    if(nestedObject && key in nestedObject) {
      return nestedObject[key];
    }
    return undefined;
  }, obj);
}

Use as follows in your code:

return deepAccessUsingString(it, keyName).toLowerCase().includes(searchText);
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.