如何过滤掉空的JSON键(null?)

时间:2013-07-21 04:31:14

标签: javascript jquery json loops null

我循环遍历JSON文件的set键。有时这些键的值将为空(null?是正确的单词?)。因此,它会在以后的交互中产生错误。我想将这些空值移除到val[]

例如JSON:

post_a: "THis is key 1"
post_b: "this is key 2"
post_c: "this is key 3"
post_d: "" 
 // I want to filiter out post_d because it is empty

循环:

 keys = ["post_a", "post_b", "post_c", "post_d"]; 
 val = [];
 $.each(keys, function(i, key) {
     val[i] = data[key];
     return val[i];
  });

目前,此循环结束后:val.length = 4如果按预期工作:val.length = 3

2 个答案:

答案 0 :(得分:1)

keys = ["post_a", "post_b", "post_c", "post_d"]; 
 val = [];
 $.each(keys, function(i, key) {
     if(data[key]){
       val[i] = data[key];
       return val[i];
     }
  });

您的代码中没有空检查。它只是随时添加所有内容。试试上面的

答案 1 :(得分:1)

if (data[key]) {
    // var is defined, do your code
}