slash-bang slash-bang - 3 years ago 74
HTML Question

Loop into Javascript object and show in table

I am using JavaScript JSON object. I am not sure this is the right way to write JSON object :-

var address={
details:{
"martin":[{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}],
"luthar":[{"full_name":"Luther king"},{"address":"Boston"},{"phone":"9856568789"}],
"jonson":[{"full_name":"Jonson vierra"},{"address":"New york"},{"phone":"98654567887"}]
}
}


Now, I want to show every elements of each person in a table. I can do this manually by writing:

<table border=1>
<tr>
<td><script>document.write(address.details.martin[0].full_name)</script></td>
<td><script>document.write(address.details.martin[1].address)</script></td>
<td><script>document.write(address.details.martin[2].phone)</script></td>
</tr>
</table>


Like this for all 3 people, but I want to grab full details of every person by using a loop.
How can I do this easily by using a loop?

Answer Source

I would do something along these lines:

for (var i in address.details)
{
    document.write('<tr><td>' + address.details[i][0]['full_name'] + '</td><td>' + address.details[i][1]['address'] + '</td><td>' + address.details[i][2]['phone'] + '</td></tr>');
}

To follow up this code should output a table with the data you require:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>An XHTML 1.0 Strict standard template</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>

<body>
    <script>
    var address={
        details:{
        "martin":[{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}],
        "luthar":[{"full_name":"Luther king"},{"address":"Boston"},{"phone":"9856568789"}],
        "jonson":[{"full_name":"Jonson vierra"},{"address":"New york"},{"phone":"98654567887"}]
        }
    }
    </script>
    <table border=1>
    <script>
        for (var i in address.details)
        {
            document.write('<tr><td>' + address.details[i][0]['full_name'] + '</td><td>' + address.details[i][1]['address'] + '</td><td>' + address.details[i][2]['phone'] + '</td></tr>');
        }
    </script>
    </table>
</body>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download