John Abraham
John Abraham

Reputation: 18791

How to filter out JSON keys that are empty(null?)

I am looping through set keys of a JSON file. Sometimes these key's values will be empty(null? is null the proper word?). because of this it creates an error in an later interaction. I would like to remove these empty values from being sent to the val[].

Exampe 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

Loop:

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

Currently, after this loop finishs: val.length = 4 If this was to work as intended: val.length = 3

Upvotes: 1

Views: 2368

Answers (2)

vladkras
vladkras

Reputation: 17228

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

Upvotes: 1

TGH
TGH

Reputation: 39258

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];
     }
  });

There is no null check in your code. It just adds everything all the time. Try the above

Upvotes: 1

Related Questions