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
    }
});
4
  • you are checking to see if it is 'undefined' as a string. Lose the quotes: undefined Commented Mar 30, 2015 at 21:35
  • I don't think that's right... Commented Mar 30, 2015 at 21:35
  • @mcranston18 typeof always returns a string. Commented Mar 30, 2015 at 21:36
  • @Barmar my mistake. Should have read the code more thoroughly Commented Mar 30, 2015 at 21:37

1 Answer 1

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.

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

5 Comments

Hmm, I still get "Cannot read property 'toLowerCase' of undefined" when I try p.properties.st.toLowerCase()
I don't think JSON will ever create properties with undefined values. The property probably doesn't exist at all.
So why does the second code fix it but not the first (in my original post)?
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.
ahhhhhh, that makes sense. I probably need to create a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.