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?
Using JSON.If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.
if (record.has("my_object_name") && ! record. isNull("my_object_name")) { // Do something with object. }
"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types." "The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."
If you have request or response type JSON, then JSON parsing will happen. The shortest valid JSON document is a single digit number. Empty document is no valid JSON and therefore errors out.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With