如何在JavaScript中循环提取API返回JSON数组的name与percentage?
如何提取API返回数据中childCounts数组的name和percentage字段?
代码放置位置
循环代码必须放在第二个.then()的回调函数中——也就是你当前打印data is的位置。因为只有在这个阶段,API返回的JSON数据已经被成功解析,你才能安全地访问data.data.childCounts数组。
具体实现方法
以下是几种常用的循环提取方式,你可以根据需求选择:
方式1:使用forEach直接遍历处理
适合需要逐个处理每个子项的场景:
.then(data => { // 遍历childCounts数组 data.data.childCounts.forEach(item => { const { name, percentage } = item; console.log(`房间名称:${name},占比:${percentage}`); // 这里可以添加你的业务逻辑,比如渲染到页面 }); })
方式2:使用for...of循环
ES6迭代语法,可读性强:
.then(data => { const childCounts = data.data.childCounts; for (const item of childCounts) { const name = item.name; const percentage = item.percentage; console.log(name, percentage); // 执行你的业务操作 } })
方式3:使用map生成新数组
如果需要把提取的字段整理成一个新数组(比如后续要批量处理),推荐用map:
.then(data => { // 生成只包含name和percentage的新数组 const roomStats = data.data.childCounts.map(item => ({ roomName: item.name, roomPercentage: item.percentage })); console.log('整理后的房间数据:', roomStats); // 后续可以使用roomStats做其他操作 })
完整修改后的代码
把上述任意一种方式替换原代码中第二个.then()的内容即可,比如用forEach的完整代码:
<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 => { // 遍历childCounts并提取字段 data.data.childCounts.forEach(item => { const { name, percentage } = item; console.log(`房间:${name},占比:${percentage}`); // 在这里添加你的业务逻辑,比如将数据插入DOM }); }) .catch(error => { if (error.status === 404) { // 处理404逻辑 } }); </script>
内容的提问来源于stack exchange,提问作者w2012z
相关产品推荐
相关产品推荐

