Reputation: 6252
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 ?
Upvotes: 2
Views: 1711
Reputation: 68943
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);
}
}
Upvotes: 8
Reputation: 10081
item.Id != "01" || item.Id !="02"
will always be true, as it can't be equal to both of the values at the same time.
You only need to use &&
instead of ||
:
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")
{
console.log(item.Id); // I prefer consoling, that's less agressive!
}
}
⋅ ⋅ ⋅
If you also plan to do if(item.Id != "01" && item.Id !="02" && item.Id !="03")
, you must want to use a >
comparator and unary +
on your string:
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 > 2)
{
console.log(item.Id); // I prefer consoling, that's less agressive!
}
}
Hope it helps.
Upvotes: 1
Reputation: 33726
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);
}
}
Upvotes: 1