0
votes

Is there the possibility of iterating over an interface properties in an elegant way and return a result based on a certain logic. I have an interface and I want to read the properties values to see if the values are empty or not and based on that I determine a final result.

Interface is :

 errors: {
    confirmPassword: "",
    email: "",
    firstname: "",
    lastname: "",
    password: ""
  }

Now, I want to iterate through the properties and if anyone of them has some value, I return a true or false if all of them are empty.

3
Loop through Object.values(<object>) of an object which implements the interface? - adiga

3 Answers

0
votes

You can also use the Array method .some()

let errors= {
confirmPassword: "",
email: "",
firstname: "",
lastname: "",
password: ""
  };
let allNull = Object.keys(errors).some(function(k) {
    return errors[k] === "";
});
console.log(allNull);
0
votes

No, you cannot iterate over interface properties as the interface doesn't exists in runtime.

You can iterate over object properties with obj.hasOwnProperty(prop)

var buz = {
    fog: 'stack'
};

for (var name in buz) {
    if (buz.hasOwnProperty(name)) {
        alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
    }
    else {
        alert(name); // toString or something else
    }
}
-2
votes

You can use Object.values and Array.every

let errors =  {
    confirmPassword: "",
    email: "",
    firstname: "",
    lastname: "",
    password: ""
};

let result = Object.values(errors).every(v => v == "");
console.log(result);

Or you can simply use a for loop for the same.

let errors = {
  confirmPassword: "",
  email: "",
  firstname: "",
  lastname: "",
  password: ""
};

let result = true;
for (let key in errors) {
  if(errors[key] != "") {
    result = false;
    break;
  }
}
console.log(result);