大家好!我需要在屏幕上显示 API 的第一个对象:http://dummy.restapiexample.com/api/v1/employees

Hi, everyone! I need to show on the screen FIRST object of the API: http://dummy.restapiexample.com/api/v1/employees

<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>

这是我的尝试,它显示了所有对象,但我只需要第一个

<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>

假设数据是一个对象数组,您可以像在任何数组中一样选取第一个元素。没有看到符合逻辑的响应结构。

由于 API returns 具有 successdata 属性的对象,我会认为您想要第一个 data 对象,所以第一个员工。

看文档Working with objects,必备知识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>