Check whether or not the attribute value of a JSON exists?

0

When checking if the following values exist for the "propertyName" attribute, I want it to show it to me if it does not exist . But the problem is that I get repeated values , as many times as objErrList.length there is. If it finds value, it does not repeat itself, but if it does not find it, it repeats the whole list, how can I solve it?

You can run the code to see what happens

var errorList = '[{"propertyName":"nombre","error":"wrong"},{"propertyName":"direccion","error":"wrong"},{"propertyName":"email","error":"right"}]';

var objErrList = JSON.parse(errorList);

for(var j = 0; j < objErrList.length; j++) {

    if (objErrList[j].propertyName === "email") {
        console.log("existe email");
    }
    if (objErrList[j].propertyName === "nombre") {
        console.log("existe nombre");
    }
    if (objErrList[j].propertyName === "ciudad") {
        console.log("existe ciudad");
    } else {
    console.log("no existe ciudad");
    }
    if (objErrList[j].propertyName === "dni") {
        console.log("existe dni");
    } else {
    console.log("no existe dni");
    }
    if (objErrList[j].propertyName === "pais") {
        console.log("existe pais");
    } else {
    console.log("no existe pais");
    }
    if (objErrList[j].propertyName === "provincia") {
        console.log("existe provincia");
    } else {
    console.log("no existe provincia");
    }
}
    
asked by Norak 21.09.2017 в 13:08
source

1 answer

2

You can create an array with the properties to search and check if there is an element with that property name:

var errorList = '[{"propertyName":"nombre","error":"wrong"},{"propertyName":"direccion","error":"wrong"},{"propertyName":"email","error":"right"}]';

var objErrList = JSON.parse(errorList);

var properties = ['email', 'nombre', 'ciudad', 'dni', 'pais', 'provincia'];

for (var j = 0; j < properties.length; j++) {
  console.log(
    (objErrList.find(function(x) {return x.propertyName===properties[j];}) ? '' : 'no ') +
    'existe ' + properties[j]
  );
}
    
answered by 21.09.2017 / 13:18
source