Home > front end >  Hi, everyone! I need to show on the screen FIRST object of the API: http://dummy.restapiexample.com/
Hi, everyone! I need to show on the screen FIRST object of the API: http://dummy.restapiexample.com/

Time:12-31

<body>
<h1>This is a page</h1>
<div id="page"></div>
<script>
    fetch("http://dummy.restapiexample.com/api/v1/employees")
       .then(response => response.json())
       .then(data => {
           console.log(data)
           document.querySelector("#page").innerText = JSON.stringify(data)
       })
</script>

here is my try, which shows all objects, but I need only the first one

CodePudding user response:

<body>
<h1>This is a page</h1>
<div id="page"></div>
<script>
    fetch("http://dummy.restapiexample.com/api/v1/employees")
       .then(response => response.json())
       .then(data => {
           console.log(data[0]) //notice the index in data
           document.querySelector("#page").innerText =JSON.stringify(data[0])
       })
</script>

That would be assuming the data is an array of objects, you could pick up the first element as you would in any array. Without seeing the response structure that would be the logical approach.

CodePudding user response:

Since the API returns an object with success and data attributes, I'll consider you want the first data object so the first employee.

Look at Working with objects on documentation, it's must-have knowledge in Javascript.

<body>
  <h1>This is a page</h1>
  <div id="page"></div>
  <script>
    fetch('http://dummy.restapiexample.com/api/v1/employees')
      .then(response => response.json())
      .then(data => {
        document.body.innerText = JSON.stringify(data.data[0]);
      });
  </script>
</body>

  • Related