Search code examples
javascripthtmlcsscss-grid

How to render keys and values from JSON into a grid


I have a large JSON file (sample below) that I am trying to arrange into a well formatted grid. This is what I have right now:

const txt = '[{"prompts": "Breakfast","text": "The breakfast table is a microcosm of the wider world. How do we understand the people around us"},{"prompts": "Water Balloons","text": "This studio looks at the concept of water-balloons or rubber balloons"}]'


const obj = JSON.parse(txt);
let text = "";
for (let i = 0; i < obj.length; i++) {
  text = obj[i].prompts;
  names = obj[i].text;

}
  let prompt = document.createElement("div");
prompt.setAttribute("class", "box");
prompt.innerHTML = text;
document.getElementsByClassName("wrapper")[0].appendChild(prompt);

let output = document.createElement("div");
output.setAttribute("class", "box");
output.innerHTML = names;
document.getElementsByClassName("wrapper")[0].appendChild(output);
body {
  margin: 40px;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.box:nth-child(even) {
  background-color: #ccc;
  color: #000;
}

    .wrapper {
        display: grid;
    grid-gap: 10px;
        grid-template-columns: repeat(1, minmax(100px,1fr) minmax(200px,2fr));
    }
<div class="wrapper">
  <div class="box">1</div>
  <div class="box">2</div>
</div>

However, this only prints the last item: enter image description here

I want to print out all items, what am I doing wrong? The keys should be in the black box and the values printed in the white box.


Solution

  • Yes It always print the last one! because you are not appending element inside the loop, so that's why only last element get saved in text and names variable, Please modify your JavaScript code like below

    const txt = '[{"prompts": "Breakfast","text": "The breakfast table is a microcosm of the wider world. How do we understand the people around us"},{"prompts": "Water Balloons","text": "This studio looks at the concept of water-balloons or rubber balloons"}]'
    
    
    const obj = JSON.parse(txt);
    for (let i = 0; i < obj.length; i++) {
      let text = obj[i].prompts;
      let names = obj[i].text;
      
      let prompt = document.createElement("div");
      prompt.setAttribute("class", "box");
      prompt.innerHTML = text;
      document.getElementsByClassName("wrapper")[0].appendChild(prompt);
    
      let output = document.createElement("div");
      output.setAttribute("class", "box");
      output.innerHTML = names;
      document.getElementsByClassName("wrapper")[0].appendChild(output);
    }
    

    Output enter image description here