Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert JSON Data into HTML

I came across an exercise in freeCodeCamp to convert json data to html. Here, I was asked to copy paste a jquery which I didn't understand.

json.forEach(function(val) {
  var keys = Object.keys(val);
  html += "<div class = 'cat'>";
  keys.forEach(function(key) {
    html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
  });
  html += "</div><br>";
});

This is my json

[  
   {  
      "id":0,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
      "altText":"A white cat wearing a green helmet shaped melon on it's head. ",
      "codeNames":[  
         "Juggernaut",
         "Mrs. Wallace",
         "Buttercup"
      ]
   },
   {  
      "id":1,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
      "altText":"A white cat with blue eys, looking very grumpy. ",
      "codeNames":[  
         "Oscar",
         "Scrooge",
         "Tyrion"
      ]
   },
   {  
      "id":2,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
      "altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
      "codeNames":[  
         "The Doctor",
         "Loki",
         "Joker"
      ]
   }
]

Can anyone help me to break down this code and tell what each line in the code does? For example I don't know what Object.keys does. Is Object an inbuilt instance?

like image 700
Gaurav Thantry Avatar asked Apr 19 '26 21:04

Gaurav Thantry


1 Answers

The Object.keys() method returns an array of a given object's own enumerable properties.

var keys = Object.keys(val);

Here 'keys' is the array form of your json. According to the JSON you provided the array has 3 objects.

You can also write

Object.keys(val).forEach(function(key){
  //something
});

instead of

var keys = Object.keys(val);

keys.forEach(function(key) {
     //something
  });

Inside the loop the key returns the the key of your object i.e. id, imageLink etc and val[key] return corresponding values e.g. 0, "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg" to be more specific.

like image 192
Hq Shiblu Avatar answered Apr 22 '26 14:04

Hq Shiblu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!