How to repeat div with json with dynamic content?

Asked

Viewed 49 times

-1

Right now I want to make a div have a JSON content. In this case, the first div has the "0" content of JSON, and that repeats itself in loop, until it reaches the maximum amount of items within JSON.

[...]
<section>
<div>
<p id="nome">Texto</p>
</div>               
</section>
[...]

JSON

var jsonnomes = {
    "status": "ok",
    "totalResults": 3,
    "nomes": [{
        "name": "Pedro",
        "idade": "33"
    }, {
        "name": "Bruno",
        "idade": "27"
    }, {
        "name": "Julia",
        "idade": "25"
    }]
}

Code I am currently using to call JSON is this:

function main() {
    let data = jsonnomes
    let newsJSON = JSON.parse(data);
    console.log(newsJSON.articles);
    const keys = Object.keys(newsJSON.nomes);
    keys.forEach(key => {
        var Autor = document.getElementById("nome").innerHTML += newsJSON.articles[key]["name"] + "<br>";
    })

I don’t know if I have to create another function for the loop or if I can put next to this "main" function. I also don’t know how to do this code. Who can help me thank.

Just remember that the goal is to repeat the div with its style, changing only the content within it. Content this that is in a JSON.

2 answers

1


HTML:

<section>
</section>

Javascript:

const section = document.querySelector('section');
const arr = [];
const jsonnomes = {
    "status": "ok",
    "totalResults": 3,
    "nomes": [{
        "name": "Pedro",
        "idade": "33"
    }, {
        "name": "Bruno",
        "idade": "27"
    }, {
        "name": "Julia",
        "idade": "25"
    }]
}

const renderInfos = () => {
const { nomes } = jsonnomes;
    const res = nomes.forEach((item) => {
    arr.push(`
      <div>
        <p>Nome: ${item.name} - Idade: ${item.idade}</p>
      </div>    
    `)
  })
section.innerHTML = arr.join(' ');  
}

renderInfos()

Example: https://jsfiddle.net/ax9hgLkf/

0

test the following code

    var jsonnomes = {
      "status": "ok",
      "totalResults": 3,
      "nomes": [{
        "name": "Pedro",
        "idade": "33"
      }, {
        "name": "Bruno",
        "idade": "27"
      }, {
        "name": "Julia",
        "idade": "25"
      }]
    }
    
    var wData = jsonnomes.nomes;
    var wHtml = ""
    for (let wIdx = 0; wIdx < wData.length; wIdx++) {
      const wElement = wData[wIdx];
      wHtml += "Nome : " + wElement["name"] + "  Idade :" + wElement["idade"] + "<br>"

}
document.getElementById("nome").innerHTML += wHtml
  • It works the same way as my code, pulls the json and plays everything in the same div, I think I have to change the id of <div> and <p>. It was to be in separate <div> a name in each along with its respectability.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.