views:

1562

answers:

2

I've got a json encoded dataset that I retrieve via ajax. Some of the data points I'm trying to retrieve will come back us null or empty.

However, I don't want those null or empty to be displayed to the end user, or passed on to other functions.

What I'm doing now is checking for

    if(this.cityState!='null'){
            // do some stuff here
}

However, for each line I find myself going through multiple if statements, and it seems very inefficient. Is there a better way to do this?

+1  A: 

Since JSON is simply a data format, there really is no way to know which of your data members will be null unless you explicitly check them. You can always refactor your code to make it more compact and easier to read, but you will have to check each item explicitly if you do not know beforehand which will be null and which will contain data.

While I don't know what your code is supposed to do, here is an example of how you might refactor it to make it more compact:

var data = { Name: "John Doe", Age: 25, Address: null, CityState: "Denver, CO" };
for (member in data) {
    if (data[member] != null)
     // Do work here
}
Kevin Babcock
you didn't use hasOwnProperty to check whether the property belongs to the object or added via prototype chain, for that reason i'm giving you thumbs down...
vsync
+1  A: 

I'm not completely sure of what you want to do... you say that you don't want to pass them on to other functions so I assume you want to delete them:

var data = {a:"!",b:"null", c:null, d:0, e:"", hasOwnProperty:"test"};

var y;
for (var x in data) {
    if ( Object.prototype.hasOwnProperty.call(data,x)) {
        y = data[x];
        if (y==="null" || y===null || y==="" || typeof y === "undefined") {
            delete data[x];
        }

    }
}

The check for hasOwnProperty is to make sure that it isn't some property from the property chain.

some