How to make a correct if within a foreach?

2

I have an input of type text there is entered an id to verify if you existed or not.

list.forEach(function(a) {
    if (b == a["id"]) {
        g["setstatus"](true, a["id"], f);
        return c(true)
        alert("Correcto!");
    }
    g["setstatus"](false, null, f);
    return c(false)
});

The data I receive within the foreach is JSON type

[
  {"id":2,"email":"[email protected]","name":"User example 3","c":false},
  {"id":2,"email":"[email protected]","name":"User example 2","c":false},
  {"id":1,"email":"[email protected]","name":"User Example 1","c":false}
]

The problem is when verifying b == a["id"] , in this case b is the variable that receives the value of the user.

When I put 3 or 2 in the input it does not recognize, but when I put 1 newly recognize, I know it's the foreach, I also did it this way:

a.forEach(function(a) {
    if (b == a["id"]) {
        g["setstatus"](true, a["id"], f);
        alert("Correcto!");
        return c(true)
    }

});
g["setstatus"](false, null, f);
return c(false)

But unfortunately it did not work either.

    
asked by Jhosselin Giménez 22.05.2017 в 23:52
source

1 answer

3

The reason why your sentence is failing for values where b!=1 is because your condition does not break the foreach and therefore will always evaluate the other values (which would be false)

Example: b = 3

# primer ciclo, a = {"id":3,"email":"[email protected]","name":"User example 3","c":false}
# se activa el botón porque la sentencia b = a["id"], se cumple

# segundo ciclo, a = {"id":2,"email":"[email protected]","name":"User example 2","c":false}
# se desactiva el botón porque la sentencia deja de cumplirse.

The reason why b=1 is always activated is because it is the last item in your list and therefore there is no next one that deactivates the button.

One possible solution would be to stop using the foreach and instead do:

var exist = list.some(function(a) {
  return b == a["id"]; // or b == a.id;
});

if(exist) {
  g["setstatus"](true, a["id"], f);
  alert("Correcto!");
}

You can see more about the use of some here

    
answered by 23.05.2017 / 01:12
source