Jennifer Jennifer - 7 months ago 12
Javascript Question

validation using forEach to get property key

var field_arr = [{name:name},{email:email},{tel:tel}];
field_arr.forEach(function(obj,i){
console.log(obj);
})


How to get the value of name, email or tel (property key)? I want to use loop to prompt user what is missing. Like if user missed tel, there will be an alert saying
tel is missing
.

Answer

I don`t think you need it to be an array. Just loop over all the properties of your JSON object.

 var obj = {
   name: "name",
   email: "",
   tel: "tel"
 };
 $.each(obj, function(key, value) {
   if (value == "") {
     console.log(key + ": " + value);
   }

 });