msqar msqar - 3 years ago 322
HTML Question

html table based upon json object tree

I've got a dynamic json object that can contain different types of attributes and objects inside, could have plane strings or even arrays.
I made a javascript code to convert a single JSON structure to an HTML table, worked great but id like to make it for a dynamic JSON, so basically I would need to iterate through the JSON tree parents and childs to see how do i create this HTML table.

But I do have some problems when trying to validate if a child has an object inside, like this: ( I don't want to add to many details to the JSON)

parent: {
child_1: {
attr1 : value1
child_2: {
[{ attribues and values in an array }]

How could I achieve this? I was thinking of using the "typeof" function like so:

if (typeof key === 'array') {
// do something
// do another stuff

But I don't believe it would work well, can you guys help me?

Thanks in advance.

Answer Source

Checking typeof key === 'array' is incorrect since for arrays typeof will return "object". You can try to use instanceof instead:

if (key instanceof Array) {
    // do something
} else {
    // do another stuff

But this will fail if your JSON was created in another frame. Another option is to check toString()'Array') > 0

or to check


but it does not supported by all browsers.

Description of typeof you can see here

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