2

For example, I want to see if response.objects[0].images[0].url exists (and isn't null)

What would be the most proper way to verify if the url property exists in the object?

If I just did

if (response.objects[0].images[0].url !== undefined && response.objects[0].images[0].url !== null {
  console.log(response.objects[0].images[0].url);
}

But then it can lead to issues if any of the properties before the url one are themselves undefined or null.

Should I deeply nest and verify if each of the previous properties are either not null and not undefined as well?

  • if(x!=null) hits both undefined and null in one comparison... – dandavis Jun 13 '14 at 00:35
  • If something before (nested not as far) as what you are checking is null , doesn't that answer your question that the one you are checking is null? – Scott Selby Jun 13 '14 at 00:36
  • 1
    put it in a try catch , if fails - you know it or it's parent is null, or actually check each layer like this answer for same question http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object – Scott Selby Jun 13 '14 at 00:37
  • @ScottSelby: If you detect a "same question", you should just [vote to close](http://stackoverflow.com/help/privileges/close-questions) as a duplicate – Bergi Jun 13 '14 at 01:37
  • thanks , will do next time – Scott Selby Jun 13 '14 at 01:44

1 Answers1

1

use a resolver:

function resolve(start) {
    return [].slice.call(arguments, 1).reduce(function(obj, prop) {
        return obj && obj[prop];
    }, start);
}


resolve(response, "objects", 0, "images", 0, "url");

if it returns undefined, then something along the way went bad...

dandavis
  • 16,370
  • 5
  • 40
  • 36
  • How about: `[].reduce.call(arguments, function(obj, prop){` – elclanrs Jun 13 '14 at 00:40
  • @elclanrs: I feed 1 to the slice(), it's not just there "for tradition"... ;) – dandavis Jun 13 '14 at 00:40
  • 1
    Yeah, just noticed, I do this http://stackoverflow.com/questions/18891939/javascript-retrieve-object-property-path/18892019#18892019. There are probably other dups around. – elclanrs Jun 13 '14 at 00:41
  • @elclanrs: dots are nice too, unless the key has dots. an array works as well as arguments, and avoids any name conflicts with the handy and tempting string path. I like String(arr).split(/[.,]/) in controlled environments where i want flexibility like that... – dandavis Jun 13 '14 at 00:44
  • @alex: slice always creates a new array, and it's generic, which means it works on array-like things like arguments and strings by using _this_ as an array. slice's first argument is the left-side starting position, which we want to be 1 instead of 0 so that we have room for the object. putting it altogether, we call a generic method, [].slice, setting _this_ to arguments and the start pos to 1, which outputs an new array like _this_, chopped as specified before returning. – dandavis Jun 13 '14 at 01:20