API JSON javascript提取数据循环数组

yyhrrdl8  于 2023-02-26  发布在  Java
关注(0)|答案(4)|浏览(146)

我已经使用以下方法成功地从API连接和获取JSON数据:

<script type="text/javascript"> 
   fetch('https://api.web_address.com/vi/locations/10', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my_bearer_token'
    },
})
.then(response => {
    if (response.ok) {
      return response.json()

    } else {
      return Promise.reject({
        status: response.status,
        statusText: response.statusText
      })
    }
  })
.then(data => console.log('data is', data))
.catch(error => {
    if (error.status === 404) {
      // do something about 404
    }
  })
</script>

API提供以下数据:

{
    "message": "OK",
    "data": {
        "id": 10,
        "name": "First floor",
        "count": 96,
        "percentage": 0.06,
        "timestamp": "2023-02-25T03:53:25.279Z",
        "isActive": true,
        "childCounts": [
            {
                "id": 11,
                "name": "Room 101",
                "count": 36,
                "percentage": 0.1,
                "isActive": true
            },
            {
                "id": 12,
                "name": "Room 102",
                "count": 17,
                "percentage": 0.06,
                "isActive": true
            },
            {
                "id": 13,
                "name": "Room 103",
                "count": 12,
                "percentage": 0.04,
                "isActive": true
            }
        ]
    }
}

我如何循环得到“名称”和“百分比”?我把循环放在哪里?希望描述是清楚的,因为我已经尝试和尝试,不能得到任何工作...请帮助!

y3bcpkx1

y3bcpkx11#

.data.childCounts上循环。

let o = { "message": "OK", "data": { "id": 10, "name": "First floor", "count": 96, "percentage": 0.06, "timestamp": "2023-02-25T03:53:25.279Z", "isActive": true, "childCounts": [ { "id": 11, "name": "Room 101", "count": 36, "percentage": 0.1, "isActive": true }, { "id": 12, "name": "Room 102", "count": 17, "percentage": 0.06, "isActive": true }, { "id": 13, "name": "Room 103", "count": 12, "percentage": 0.04, "isActive": true } ] } };
for (const {name, percentage} of o.data.childCounts) {
  console.log(name, percentage);
}
1bqhqjot

1bqhqjot2#

我的回答:

let o = { "message": "OK", "data": { "id": 10, "name": "First floor", "count": 96, "percentage": 0.06, "timestamp": "2023-02-25T03:53:25.279Z", "isActive": true, "childCounts": [ { "id": 11, "name": "Room 101", "count": 36, "percentage": 0.1, "isActive": true }, { "id": 12, "name": "Room 102", "count": 17, "percentage": 0.06, "isActive": true }, { "id": 13, "name": "Room 103", "count": 12, "percentage": 0.04, "isActive": true } ] } };

o.data.childCounts.map((ele)=> {
  const {name, percentage} = ele;
  console.log(name, percentage)
})

希望能对你有所帮助。

2nbm6dog

2nbm6dog3#

我的回答是:

<script type="text/javascript"> 
   fetch('https://api.web_address.com/vi/locations/10', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my_bearer_token'
    },
})
.then(response => {
    if (response.ok) {
      return response.json()

    } else {
      return Promise.reject({
        status: response.status,
        statusText: response.statusText
      })
    }
  })
.then(rawData => { // Add another 'then' block here
    const {data: {childCounts = []} = {}} = rawData; //default values when destructuring
    return childCounts.map(({name = '', count = 0}) => ({ // always good to have defaults
        name,
        count
    }))
})
.then(data => console.log('data is', data)) // Now this data is the data you want
.catch(error => {
    if (error.status === 404) {
      // do something about 404
    }
  })
</script>

注意:如果你正在处理承诺,尝试使用async/await。

xqkwcwgp

xqkwcwgp4#

您可以使用map方法和object destructuring语法:

const data = {"message":"OK","data":{"id":10,"name":"First floor","count":96,"percentage":0.06,"timestamp":"2023-02-25T03:53:25.279Z","isActive":true,"childCounts":[{"id":11,"name":"Room 101","count":36,"percentage":0.1,"isActive":true},{"id":12,"name":"Room 102","count":17,"percentage":0.06,"isActive":true},{"id":13,"name":"Room 103","count":12,"percentage":0.04,"isActive":true}]}};

const processData = (data) => {
  const { childCounts } = data.data || {};
  return childCounts ? childCounts.map(({ name, percentage }) => ({ name, percentage })) : [];
a;
}

console.log(processData(data));
console.log(processData({})); // []

相关问题