Foreach in Javascript

0
Hello, I have an object in JavaScript and I would like to check if all values of the object keys are different from null , undefined , 0, "" and "".

I run each value of my object with forEach , however I want the first condition to be executed only if all the values are different than the one I commented above.

In my code, if only one value is no longer null , undefined , 0, "" or "", my code executes the condition and does not enter else else.

Beautified JavaScript :

let dados = {
    nome: nome,
    email: email,
    telefone: telefone,
    cursos: cursos,
    cidade: cidade
};
let condicao = false;
Object.values(dados).forEach(function (campo) {
    console.log(campo);
    if (campo !== "" && campo !== null && campo !== " " && campo !== false && campo !== 0 && campo !== undefined) {
        //Execute algo
    } else {
        if (condicao == false) {
            alert("Preencha todos os campos");
            condicao = true;
        }
    }
})

Can anyone help me?

    
asked by anonymous 04.01.2019 / 14:50

2 answers

0

Out of a method, I imagine the resolution in a simple and verbose way as follows:

let dados = { nome: '', email: 'email', telefone: 'telefone', cursos: 'cursos', cidade: 'cidade' };

let count = 0;

Object.values(dados).forEach(function (campo) {
    if (!campo || campo === ' ') {
        count++;
    }
});

if (count === 0) {
    console.log('todos preenchidos');
} else {
    console.log('falta preencher');
}

Just look at some details:

  • In javascript, 0, null, undefined and blank are values that return false, so in a check if you use "! var", for any of those values that is in the variable, will return false;
  • You used "& &" for verification, in this case the value of a variable would have to be, according to its example, null, blank, undefined, etc ... and it is impossible for a value to have all these attributes rsrs, in which case you should use "||" so if the value has any of these conditions, it returns false

I hope I have helped, good luck.

    
04.01.2019 / 19:00
2

The object in JS is of type key-value.

You can use for ... in, follow the documentation below

//Objeto
var obj = {a:1, b:2, c:3};

//Para prop (propriedade) in obj (objeto) faça
for (var prop in obj) {
  // ctrl+shift+k (para abrir o console no mozilla firefox)
  console.log("obj." + prop + " = " + obj[prop]);
}

//A saída (output) deverá ser:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

Reference: link

    
04.01.2019 / 15:11