Reputation: 593
I have found and tried out .includes
to help with this problem. But .includes
did not work as I intended. It actually did find one item in the JSON that matched the value in the other array, but it only matched similar values:
result_postid array:
[10,22,12,36,45,206]
item.id from JSON data:
[{"id":"5","username":"Mike"},{"id":"13","username":"Tom"},{"id":"28","username":"Jake"},{"id":"136","username":"Josie"},{"id":"400","username":"Bill"},{"id":"538","username":"Sam"}]
I tried to figure out why some of the values kept returning true
when they should be clearly false
. Then I came to the conclusion that .includes
was actually taking 36
from result_postid
and matching it with 136
in item.id
. This is how I setup the if statement with .includes
:
{result_postid.includes(item.id) ?
<Text>True</Text>
:
<Text>False</Text>
}
This is the result:
result_postid | item.id | Result
10 != 5,13,28,136,400,538: False
22 != 5,13,28,136,400,538: False
12 != 5,13,28,136,400,538: False
36 = 5,13,28,136,400,538: True <--- this should be false
45 != 5,13,28,136,400,538: False
206 != 5,13,28,136,400,538: False
Then I tried this attempt with Lodash:
{_.intersection(item.id, result_postid) ?
<Text>True</Text>
:
<Text>False</Text>
}
And the results all came true
, which is not correct:
10 = 5,13,28,136,400,538: True
22 = 5,13,28,136,400,538: True
12 = 5,13,28,136,400,538: True
36 = 5,13,28,136,400,538: True
45 = 5,13,28,136,400,538: True
206 = 5,13,28,136,400,538: True
Is it possible to even compare values in an array to JSON data and show whether one value equal each other, if so true? If not, false?
Upvotes: 1
Views: 206
Reputation: 18515
Here is a way to get the results you want. Since you are comparing strings to integers your results are not as what you would expect.
var data = [{"id":"5","username":"Mike"},{"id":"13","username":"Tom"},{"id":"28","username":"Jake"},{"id":"136","username":"Josie"},{"id":"400","username":"Bill"},{"id":"538","username":"Sam"}]
var arr = [10,22,12,36,45,206]
console.log(data.map(({id}) => arr.includes(+id)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
By doing the +id
you are converting the string to number before the next operation.
Upvotes: 1