jQuery如何动态遍历json对象

时间:2014-11-10 16:25:10

标签: javascript jquery ajax json

我使用ajax验证我的公式,并获取以下json对象:

{"username":["Please enter a username"],"email":["Please enter an email"],
"plainPassword":{"first": ["Please enter a password"]},"firstname":
["This value should not be blank."],"lastname":["This value should not be blank."],
"terms":["This value should be true."],"privacy":["This value should be true."],
"captcha":["Code does not match"],"securityQuestion":["This value should not be blank."],
"plainSecurityAnswer":["This value should not be blank."],"intention":
["This value should not be blank."],"addresses":[{"state":["This value should not be blank."],
"city":["This value should not be blank."],"zipcode":["This value should not be blank."],
"country":["This value should not be blank."]}]}

键总是通过以下方式映射到输入字段id:     var id =“fos_user_registration_form_”+ key;

我希望以有效的方式将这些错误呈现为字段的工具提示。为此,我编写了以下jQuery代码(其中回调是返回的json对象):

$.each( callback, function( key, entry ) {
    if(key != "addresses" && key != "plainPassword")
      {
         var id = "#fos_user_registration_form_" + key;
         $(id).tooltip('destroy');
         $(id).tooltip({'title': entry});
         $(id).closest('div[class="form-group"]').addClass('has-error');
      }else if(key == "addresses"){
         $.each( entry[0], function( keyAddress, entryAddress ) {
             var id = "#fos_user_registration_form_" + key + "_0_" + keyAddress;
             $(id).tooltip('destroy');
             $(id).tooltip({'title': entryAddress});
             $(id).closest('div[class="form-group"]').addClass('has-error');
         });
       }else if(key == "plainPassword")
         {
           var id= "#fos_user_registration_form_plainPassword_first,#fos_user_registration_form_plainPassword_second";
           $(id).tooltip('destroy');
           $(id).tooltip({'title': entry.first});
           $(id).closest('div[class="form-group"]').addClass('has-error');
}});

它正在工作,但我认为不是很动态,因为我知道在这种情况下,键“address”和“plainPassword”的条目不是字符串,我必须再次迭代它们(这里只在地址上) )。

有没有一种更好的方法可以通过仅使用循环的键和入口变量来实现这一点,而不知道json的“关键”名称?

我想到了类似的东西:while entry!==“string”,迭代条目,因为其中有另一个数组或对象,并构建“id”变量。当字符串字段为“条目”时,请将其用作工具提示文本。

希望你们能帮帮我。

问候。

2 个答案:

答案 0 :(得分:0)

递归会做到这一点!

例如http://repl.it/3hK/5

代码 -

var id_stub = "#fos_user_registration_form_"

// Here's the recursive function - we kick it off below.
function process(thing, id) {
    var key
    for (key in thing) {
        // Handle the arrays
        if ('length' in thing[key]) {

            // Handle the end - we found a string
            if (typeof thing[key][0] == "string") { 
                var html_id = id_stub + id + key
                var err_msg = thing[key][0]

                console.log(html_id, ":", err_msg)

                // Now do your jquery using the html_id and the err_msg...
            }
            // Else we found something else, so recurse.
            else {
                var i = 0;
                while (i < thing[key].length) {
                    process(thing[key][i], key + "_" + i + "_")
                    i++
                }
            }
        }

        // Handle the objects by recursing.
        else {
            process(thing[key], key + "_")
        }
    }
}

// Start the recursion from here.
process(callback, "")

我添加了一个额外的地址来测试此代码如何处理嵌套地址,并使用它在控制台中得到它:

#fos_user_registration_form_username : Please enter a username
#fos_user_registration_form_email : Please enter an email
#fos_user_registration_form_plainPassword_first : Please enter a password
#fos_user_registration_form_firstname : This value should not be blank.
#fos_user_registration_form_lastname : This value should not be blank.
#fos_user_registration_form_terms : This value should be true.
#fos_user_registration_form_privacy : This value should be true.
#fos_user_registration_form_captcha : Code does not match
#fos_user_registration_form_securityQuestion : This value should not be blank.
#fos_user_registration_form_plainSecurityAnswer : This value should not be blank.
#fos_user_registration_form_intention : This value should not be blank.
#fos_user_registration_form_addresses_0_state : This value should not be blank.
#fos_user_registration_form_addresses_0_city : This value should not be blank.
#fos_user_registration_form_addresses_0_zipcode : This value should not be blank.
#fos_user_registration_form_addresses_0_country : This value should not be blank.
#fos_user_registration_form_addresses_1_state : This value should not be blank.
#fos_user_registration_form_addresses_1_city : This value should not be blank.
#fos_user_registration_form_addresses_1_zipcode : This value should not be blank.
#fos_user_registration_form_addresses_1_country : This value should not be blank.

并设置执行jQuery工作所需的变量。

答案 1 :(得分:0)

   function isValidationMessage(entry) {
      return entry.length === 1 && typeof entry[0] === 'string';
    }

function displayValidationMessage(key, message){
  var id = "#fos_user_registration_form_" + key;
             $(id).tooltip('destroy');
             $(id).tooltip({'title': message});
             $(id).closest('div[class="form-group"]').addClass('has-error');
}

function displayValidationMessageForArray(key, entries) {
   for(var i = 0; i < entries.length; i++) {
     $.each(entries[i], function(keyAddress, entryAddress) {
       displayValidationMessage(key + "_i_" + keyAddress, entryAddress);
     })
   }

}

function displayValidationMessageForObject(key, entries) {
   $.each(entries, function(entry, message) {
     displayValidationMessage(key + "_" +entry, message);
   })
}

function displayAllValidationMessages(callback) {

    $.each( callback, function( key, entry ) {
        if(isValidationMessage(entry)) {
          displayValidationMessage(key, entry);
        }else if($.isArray(entry)){
           displayValidationMessageForArray(key, entry);
        }else {
           displayValidationMessageForObject(key, entry);
        }
    });
}

未完全测试,想法是将if else提取为小函数,并尽可能多地重用它们