xrcwrn xrcwrn - 4 months ago 28
jQuery Question

How to remove undefined while show json data

I am iterating customer List in jquery user each as follow

$.post("customer", {param: cid, order: order}, function (data) {
console.log(data);
$.each(data.customerList, function (i, obj) {
$("#" + tid).append('<tr><td>' + (i + 1) + '</td><td>' + obj.customerName + '</td><td>' + obj.address + '</td>'
+ '<td>' + obj.city + '</td><td>' + obj.state + '</td><td>' + obj.country + '</td><td>' + obj.mobno + '</td></tr>');
});


This code is working properly and fetching data properly .
My problem is it is showing undefined for null fields.
how to resolve this problem.

Answer

Use || "":

$.post("customer", {param: cid, order: order}, function (data) {
                    console.log(data);
               $.each(data.customerList, function (i, obj) {
                        $("#" + tid).append('<tr><td>' + (i + 1) + '</td><td>' + obj.customerName || "" + '</td><td>' + obj.address || "" + '</td>'
                                + '<td>' + obj.city || "" + '</td><td>' + obj.state || "" + '</td><td>' + obj.country || "" + '</td><td>' + obj.mobno || "" + '</td></tr>');
                    });

If the field is empty it will set an empty value instead of undefined

See following example:

var test = {
   prop1: "Test value",
   prop2: null,
   prop3: undefined
};

console.log(test.prop1 || "empty");
console.log(test.prop2 || "empty");
console.log(test.prop3 || "empty");
console.log(test.prop4 || "empty");

Comments