3

I'm trying to step through an object to make sure none of the properties are undefined. I found this question and this question and implemented the following code, but it does not work.

for (var property in p.properties) {
    if (p.properties.hasOwnProperty(property)) {
        if (typeof property == 'undefined') {
            p.properties[property] = '';
            //a breakpoint here will NOT be hit
        }
    }
}

However, if I explicitly check the one that I know has undefined values, it does work:

if(typeof p.properties.st == 'undefined') {
    p.properties.st = '';
    //a breakpoint here WILL be hit
}

Here is how the data is obtained:

$.getJSON("data/stuff.json", function (data) {
    $.each(data.features, function (i, p) {
       //checking for undefined properties here
    }
});
Community
  • 1
  • 1

1 Answers1

4

It should be:

if (typeof p.properties[property] == 'undefined')

You're testing whether the property name is undefined, which isn't possible; you want to test whether the value is undefined.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Hmm, I still get "Cannot read property 'toLowerCase' of undefined" when I try p.properties.st.toLowerCase() –  Mar 30 '15 at 21:41
  • I don't think JSON will ever create properties with undefined values. The property probably doesn't exist at all. – Barmar Mar 30 '15 at 21:43
  • So why does the second code fix it but not the first (in my original post)? –  Mar 30 '15 at 21:44
  • The difference is that a nonexistent property will never be tested in the `for` loop, because it's getting the list of properties names from the object itself. What you need is an array containing all the property names that are supposed to exist. – Barmar Mar 30 '15 at 21:47
  • ahhhhhh, that makes sense. I probably need to create a new question. –  Mar 30 '15 at 21:47