Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Javascript - Can't determine if JSON object contains true

Javascript - Can't determine if JSON object contains true


I have a Json Object I'm retrieving from a server, sometimes its really simple such as:

{ "urls": ["", ""] }

However I need to check if urls['tasks']['ipv6'] contains true, the code I'm using is:

if (urls['tasks']['ipv6'] === true) {

But because urls['tasks'] doesn't exist I get the following error:

Uncaught TypeError: Cannot read property 'ipv6' of undefined

Is there an easy way to do this? I'm having a really hard time find a Solution online. I've also tried jQuery's $.isEmptyObject and would be happy with a jQuery based solution. For reference I'm actually using this code in node.js.

Problem courtesy of: Sean Bannister


This should do the trick for you.

if (urls["tasks"] && urls["tasks"]["ipv6"] && urls["tasks"]["ipv6"] === true)

You can add urls checking at left as well if you need to and you can omit the middle check urls["tasks"]["ipv6"], because if it's undefined it definitely isn't true.

The thing is that you have to check first whether upper level properties exist before drilling down. And since Javascript (as well as majority of today's languages) doesn't use full boolean evolution this works.

Solution courtesy of: Robert Koritnik


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Javascript - Can't determine if JSON object contains true


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription