简体   繁体   中英

How to loop through a nested JSON object and save the multiple key-value pairs in Javascript

I have an interesting issue, and I have the logic of the problem down but I am not having luck coming up with a solution.

Basically, I have JSON objects (which could be of any shape or size) similar to the one listed below:

    {
  "keyHigh": {
    "title": "Sign In Page",
    "key2": {
      "keyA": "Hey!",
      "keyB": "This!",
      "keyC": "Is!",
      "keyD": "All!",
      "keyE": "Example!",
      "keyF": "Content!",
      "keyG": "Hopefully!"
    },
    "key3": {
      "keyH": "This!",
      "keyI": "Illustrates!",
      "keyJ": "My Point!",
      "keyK": "Please!",
      "keyL": "Help!"
    },
    "key4": "/test.html#/"
  }
}

Now, what I am trying to accomplish, is that I want to loop through JSON objects (similar to the one above) and produce a "keys" value pair of sorts. I am hoping to be able to produce a table like the one below, using $ to separate keys:

 <table> <tr> <th>Tag</th> <th>Content</th> </tr> <tr> <td>$keyHigh$title</td> <td>Sign In Page<br></td> </tr> <tr> <td>$keyHigh$key2$keyA</td> <td>Hey!</td> </tr> <tr> <td>$keyHigh$key2$keyB</td> <td>This!</td> </tr> <tr> <td>$keyHigh$key2$keyC</td> <td>Is!</td> </tr> <tr> <td>$keyHigh$key3$keyJ</td> <td>My Point!<br></td> </tr> <tr> <td>$keyHigh$key4</td> <td>/test.html#/</td> </tr> </table> 

NOTE**** I want all of the "tags", not just specific "tags"

How should I go about getting these multiple-key value pairs in a dynamic way?

Thank you!

I used jQuery for $.each loop and append function, but this can also be achieved with pure JS.

function layOut(keyString, obj) {
  if (typeof obj == "object") {
    $.each(obj, function (key, val) {
      layOut(keyString + "$" + key, val);
    });
  } else {
    $("table.layout").append("<tr><td>" + keyString + "</td><td>" + obj +"</td></tr>");
  }
}

The idea is to check if the deepest level is achieved. This can be done using typeof . For the start call you need to pass empty string as a keyString . So it will be layOut("", obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM