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

4
  • There is jQuery.isArray()... Commented Jan 23, 2014 at 20:52
  • See this and this Commented Jan 23, 2014 at 20:52
  • if( !! specs )? That's a double negative, why not just if(specs)? Commented Jan 23, 2014 at 20:53
  • if (specs && Array.isArray(specs) && specs.length) Commented Jan 23, 2014 at 20:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, none of these suggestions work in my fiddle so I think I might have deeper problems.
@SteveAustin The problem in your fiddle is that x isn't valid Json. See my updated answer.
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 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.
0

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

if (Object.prototype.toString.call( someVar ) === '[object Array]' ) {

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.