Skip to content
Advertisement

How to output an array individually for each object in JSON using JS?

The for (let pet of person.pets) does not output as expected. It is an array in the JSON. Instead of a single array, I get all the pet arrays for all objects in my JSON file. I just want one array per object listed in the JSON-example below.

{
   "name": "Nallil Keenwillow",
   "age": "32",
   "pets": [
     "Giddo",
     "Berl",
     "Jaenna"
   ]
 },
let persons;
let pets;

async function getData() {
  persons = await $.getJSON('persons.json');
  pets = await $.getJSON('pets.json');
  renderPersonsToScreen();
}

function renderPersonsToScreen() {
  for (let person of persons) {
    $('body').append(/*html*/`
    <div class="person">
    <h1>${person.name}</h1>
    <p>Age: ${person.age}</p>
    </div>
  `);
    for (let pet of person.pets) {
      $('.person').append(/*html*/`
      <h2>${pet}</h2>
       `
      )
    }
  }
}

getData();

Advertisement

Answer

$('.person').append() appends to all .person elements. You should just append to the person element you just added.

function renderPersonsToScreen() {
  for (let person of persons) {
    let pdiv = $( /*html*/ `
    <div class="person">
    <h1>${person.name}</h1>
    <p>Age: ${person.age}</p>
    </div>
  `);
    for (let pet of person.pets) {
      pdiv.append( /*html*/ `
      <h2>${pet}</h2>
       `)
    }
    $('body').append(pdiv);
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement