-2

I Know why I'm getting undefined but i have no idea how to solve.

Tried to put null, but it is taking in as a text

var text ='{"employees":[' +
                '{"name":"Tony","mobile":"99221111","email":"tony@json.com"},' +
                '{"name":"Linda","mobile":"98981111","email":"linda@json.com"},' +
                '{"name":"Patrick","mobile":"90902222","email":"patrick@json.com"},' +
                '{"name":"Isabella","mobile":"99552222"}]}';
    obj = JSON.parse(text);
    for(var i in obj.employees)
    {
        document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>" 
            + "<td>" + obj.employees[i].email + "</td></tr>";
    }

Hi, for Isabella there is no email, hence I'm getting undefined when I loop through to print out their details on html, however what I'm expecting is for the email portion to be empty in the table for Isabella. Is there a way to solve it?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Zac Ee
  • 31
  • 5

1 Answers1

0

You can use logical OR (|| in JavaScript), which will use the second value (empty string in this case) if the first value (email) is undefined:

var text = '{"employees":[' +
  '{"name":"Tony","mobile":"99221111","email":"tony@json.com"},' +
  '{"name":"Linda","mobile":"98981111","email":"linda@json.com"},' +
  '{"name":"Patrick","mobile":"90902222","email":"patrick@json.com"},' +
  '{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for (var i in obj.employees) {
  document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>" +
    "<td>" + (obj.employees[i].email || '') + "</td></tr>";
}
<table id="table"></table>
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55