0

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();

1 Answer 1

1

$('.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);
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.