Jennifer Jennifer - 7 months ago 17
Javascript Question

Check that array of objects has all required keys

I have an object like this :

var field_arr = [{name:name},{email:email},{tel:tel}];


How to get the value of name, email or tel (property key) ? I want to use a loop to prompt user what is missing. For example, 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);
   }

 });