peter
peter

Reputation: 1582

JS .filter() works when intereger is passed in, but not when variable is passed in

I'm trying to use the .filter to pull an object out of an array of objects.

When I do this:

var homeCountry = this.props.searchedCountry.filter(country => country.id === 7);

I get a the filtered array, but when I do this:

var homeCountry = this.props.searchedCountry.filter(country => country.id === e.target.country.value);

where e.target.country.value === 7, I get an empty array.

Can anyone explain what's going on? Thanks!

Upvotes: 0

Views: 47

Answers (2)

0.sh
0.sh

Reputation: 2752

e.target.value will be a string, but they are several ways to handle this, is either you use parseInt(e.target.value) or Number(e.target.value) or e.target.valueAsNumber. And secondly === checks the value and also the data type of the operands you are comparing therefore ( 1 === "1" ) will be evaluated as false but ( 1 === 1 ) will be evaluated as true, doing == will only compare the values, if you want to use == (non strict equal to ) it is not necessary that you should use the above suggested solution to handle the issue therefore ( 1 == 1 ) is true and ( 1 == "1" ) is also true, but if you wish to use === (which is advisable) use the above suggested solution

Upvotes: 0

front_end_dev
front_end_dev

Reputation: 2056

e.target.value is string value. you are doing strict comparison with datatype and value.

Updated Code

 var homeCountry = this.props.searchedCountry.filter(country => country.id === parseInt(e.target.country.value));

Upvotes: 1

Related Questions