This looks a simple code but not sure what I am doing wrong here.
var data = "[{\"Id\":\"01\",\"Name\":\"01- Alabama\"},{\"Id\":\"02\",\"Name\":\"02- Arizona\"},{\"Id\":\"03\",\"Name\":\"03- Arkansas\"}]";
var myJson = JSON.parse(data);
for (var key in myJson) {
var item = {
Id: myJson[key].Id,
Name: myJson[key].Name
};
if(item.Id != "01" || item.Id !="02")
{
alert(item.Id);
}
}
I am expecting to just show an alert as "03" but it shows 3 alert each for "01", "02" & "03"
Looks like != and OR operator not working ?
The || operator only returns false when both of its operands are false (and true in all other cases).
The && operator only returns true when both of its operands are true (and false in all other cases).
You have to use && instead of || in the if condition to get the expected result:
var data = "[{\"Id\":\"01\",\"Name\":\"01- Alabama\"},{\"Id\":\"02\",\"Name\":\"02- Arizona\"},{\"Id\":\"03\",\"Name\":\"03- Arkansas\"}]";
var myJson = JSON.parse(data);
for (var key in myJson) {
var item = {
Id: myJson[key].Id,
Name: myJson[key].Name
};
if(item.Id != "01" && item.Id !="02")
{
alert(item.Id);
}
}
Actually is working as expected because the OR operator is returning true for cases when Id == 01 and Id == 02
What you want to do is to join the two operands with AND operator && and this way execute the logic just when Id != 01 AND Id != 02.
var data = "[{\"Id\":\"01\",\"Name\":\"01- Alabama\"},{\"Id\":\"02\",\"Name\":\"02- Arizona\"},{\"Id\":\"03\",\"Name\":\"03- Arkansas\"}]";
var myJson = JSON.parse(data);
for (var key in myJson) {
var item = {
Id: myJson[key].Id,
Name: myJson[key].Name
};
if (item.Id != "01" && item.Id != "02") {
alert(item.Id);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With