4

I have a multiple divs returning an array like this:

[{"k":"Model","v":"box"},{"k":"Color","v":"blue"},{"k":"Size","v":"med"},{"k":"Type","v":"good"}]

Sometimes, non-array items come back and I want to ignore those.
Could be blank spaces or random un-ordered blank lists. So I only want to process only the arrays that come back leave the rest blank.
How could I check if it is array and ignore the rest?

jQuery('.overview').each(function () {
   var $overview = jQuery(this),
       specs = jQuery.parseJSON($overview.html());
   if ( !! specs) {
       $overview.html('<div class="bullet_spec"></div>');
       jQuery.each(specs, function () {
           $overview.children('div').append('<ul class="specs"><li class="label">' + this.k + ' : ' + this.v + '</li></ul>');
       });
   } else { // leave blank?? not sure what to do here
   }
});

Here is my fiddle: http://jsfiddle.net/veGPN/
Thanks

SteveAustin
  • 85
  • 1
  • 7

2 Answers2

5

You can use the isArray function from jQuery:

if (jQuery.isArray(specs)) {
   $overview.html('<div class="bullet_spec"></div>');
   jQuery.each(specs, function () {
       $overview.children('div').append('<ul class="specs"><li class="label">' + this.k + ' : ' + this.v + '</li></ul>');
   });
}

However, it appears the problem in your fiddle is that some of the elements (x) aren't even Json. So it's not that the result isn't an array, it's that it is unable to parse the result at all. You can simply wrap your parsing script with a try/catch to handle this gracefully:

var $overview = jQuery(this), spec;
try {
    specs = jQuery.parseJSON($overview.html());
} catch(e) {
    return;
}

Demonstartion

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Thanks, none of these suggestions work in my fiddle so I think I might have deeper problems. – SteveAustin Jan 23 '14 at 21:05
  • @SteveAustin The problem in your fiddle is that `x` isn't valid Json. See my updated answer. – p.s.w.g Jan 23 '14 at 22:16
  • Thanks, That works. I was weary to use try / catch after looking in to it more. I ended up simply testing for `[` and if not there leave empty. `var a = jQuery(this).text(), str = a.substr(0, 1), if (str.indexOf('[') == -1) { jQuery(this).empty(); }` This seems to work for my purposes. – SteveAustin Jan 24 '14 at 17:37
  • @SteveAustin That still wouldn't guarantee that the string was valid Json (e.g. `[+]` would pass). A `try/catch` is still safer, but yeah, maybe that's sufficient for your particular use case. – p.s.w.g Jan 24 '14 at 17:41
0

This is common and crossbrowser code to check error-free for an array :

if (Object.prototype.toString.call( someVar ) === '[object Array]' ) {
Goran.it
  • 5,991
  • 2
  • 23
  • 25