Stairss
Stairss

Reputation: 176

Fetching multiple data from JSON in lists

at the beginning I want to say that I checked a lot of solutions but none of it was straight accurate to my problem. I wonder if it's possible to fetch data from JSON (name, surname and id). In every of each list will be other data. The issue is length of lists will be as much as JSON's length so it has to be automatically generated, but unfortunately in promises, you are not allowed to make functions so what is the solution for that problem?

const nameList = document.querySelector('.name-list')
const surnameList = document.querySelector('.surname-list')
const idList = document.querySelector('.id-list')


fetch('http://www.json-generator.com/api/json/get/cuSKqtKmgi?indent=2')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });
body{
    display: flex;
    justify-content: space-around;
}
<body>
   <ul class="name-list">
    </ul>
    <ul class="surname-list">
    </ul>
    <ul class="id-list">
    </ul>
    <ul class="example">
        <li>Example1</li>
        <li>Example2</li>
        <li>Example3</li>
        <li>Example4</li>
        <li>Example5</li>
    </ul>
</body>

That is only an exercise but will help me understand fetch more. If something is unclear feel free to ask :)

Upvotes: 0

Views: 287

Answers (2)

atilkan
atilkan

Reputation: 5028

Maybe it is simple like:

let names = []
let surnames = []
let ids = []

fetch('http://www.json-generator.com/api/json/get/cuSKqtKmgi?indent=2')
.then(response => response.json())
.then(data => {        
    data.person.forEach(item => {
      names.push(item.name)
      surnames.push(item.surname)
      ids.push(item.id)
    })
});

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

You can use .forEach as follows:

const nameList = document.querySelector('.name-list')
const surnameList = document.querySelector('.surname-list')
const idList = document.querySelector('.id-list')

fetch('http://www.json-generator.com/api/json/get/cuSKqtKmgi?indent=2')
  .then(response => response.json())
  .then(data => {
    const { person = [] } = data;
    person.forEach(({ name, surrname, id }) => {
      nameList.innerHTML += `<li>${name}</li>`;
      surnameList.innerHTML += `<li>${surrname}</li>`;
      idList.innerHTML += `<li>${id}</li>`;
    });
  });
body{ display: flex; justify-content: space-around; }
<ul class="name-list"></ul>
<ul class="surname-list"></ul>
<ul class="id-list"></ul>

Upvotes: 0

Related Questions