J
J
Junior Development2020-06-18 14:55:13
JavaScript
Junior Development, 2020-06-18 14:55:13

How to display the elements of a JSON array?

Given an array

[
  {
    "id": 1,
    "name": "Allen, Miss. Elisabeth Walton",
    "age": 29,
  },
  {
    "id": 2,
    "name": "Allison, Master. Hudson Trevor",
    "age": 50,
  }
]


JS Code
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        let myArr = JSON.parse(this.responseText);

        myArr.forEach((elem, index, arr) => {
            console.log(elem.name);
        document.querySelector('.wrapper').innerHTML = elem.name;
        });

    }
};
xmlhttp.open("GET", "http://***/data.json", true);
xmlhttp.send();


It is necessary to display, for example, all elements of name in a column.
I can't figure out why it only shows one item.

5eeb555fc2fc7475369929.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Arseny, 2020-06-18
@jun_dev

1. The (elem, index, arr)second and third parameters are optional.
2. .innerHTML- overwrites everything that you output into the same element. Use appendChild at least.

X
xenonhammer, 2020-06-18
@xenonhammer

it outputs, just overwrites every time

R
Rerurk, 2020-06-18
@Rerurk

fetch('" http://***/data.json "', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}). then(r=>r.json()).then(r=>{
r.forEach(function (item) {
let span=document.createElement('span');
span.innerText=item.name;
document.body .appendChild(span);
document.body.appendChild(document.createElement('br'));
})
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question