Filtering JSON by ngModel

Viewed 30

I am currently filtering my JSON, it works fine if I filter it with a hard coded value.

Code Sample:

this.names= this.names.filter(function (name) {
    return name.last== 'lastname';
  });

It returns the object where the value of the last key is 'lastname'. However, when I use a variable to filter

Code:

this.names= this.names.filter(function (name) {
    return name.last== this.selectedLname';
  });

It shows cannot read property of 'selectedLname' in console error, but the selectedLname has a value

1 Answers

This is because this keyword in that refer to that function object. Try changing your function to arrow function and it will work.

this.names = this.names.filter((name) => {
    return name.last== this.selectedLname';
});

var data= [ {
  firstName:'abc',
  lastName: 'xyz'
},
{
  firstName:'yut',
  lastName: 'eueo'
}];
var seachKey = 'xyz'
var result = data.filter((item) => item.lastName == seachKey);
console.log(result);

Check this out

Related