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.
JavaScript
x
10
10
1
{
2
"name": "Nallil Keenwillow",
3
"age": "32",
4
"pets": [
5
"Giddo",
6
"Berl",
7
"Jaenna"
8
]
9
},
10
JavaScript
1
28
28
1
let persons;
2
let pets;
3
4
async function getData() {
5
persons = await $.getJSON('persons.json');
6
pets = await $.getJSON('pets.json');
7
renderPersonsToScreen();
8
}
9
10
function renderPersonsToScreen() {
11
for (let person of persons) {
12
$('body').append(/*html*/`
13
<div class="person">
14
<h1>${person.name}</h1>
15
<p>Age: ${person.age}</p>
16
</div>
17
`);
18
for (let pet of person.pets) {
19
$('.person').append(/*html*/`
20
<h2>${pet}</h2>
21
`
22
)
23
}
24
}
25
}
26
27
getData();
28
Advertisement
Answer
$('.person').append()
appends to all .person
elements. You should just append to the person
element you just added.
JavaScript
1
16
16
1
function renderPersonsToScreen() {
2
for (let person of persons) {
3
let pdiv = $( /*html*/ `
4
<div class="person">
5
<h1>${person.name}</h1>
6
<p>Age: ${person.age}</p>
7
</div>
8
`);
9
for (let pet of person.pets) {
10
pdiv.append( /*html*/ `
11
<h2>${pet}</h2>
12
`)
13
}
14
$('body').append(pdiv);
15
}
16
}