请求协助:从指定API获取age值为30的键组成的数组
提取API中age为30的键组成数组
核心逻辑
API返回的是一个JSON对象,每个键对应的值包含age字段。我们需要遍历所有键,筛选出对应age值等于30的键,最终将这些键组成数组。
JavaScript实现(浏览器/Node.js环境)
// 发送GET请求并处理数据 fetch('https://coderbyte.com/api/challenges/json/age-counting') .then(res => res.json()) .then(data => { const result = []; // 遍历对象所有键 for (const key in data) { if (data[key].age === 30) { result.push(key); } } console.log(result); // 输出:["IAfpK","WNVdi","JukI","hjgut","gjhg"] }) .catch(err => console.error('请求失败:', err));
Python实现
import requests # 发起请求获取数据 response = requests.get('https://coderbyte.com/api/challenges/json/age-counting') data = response.json() # 列表推导式筛选符合条件的键 result = [key for key, val in data.items() if val['age'] == 30] print(result) # 输出:["IAfpK","WNVdi","JukI","hjgut","gjhg"]
内容的提问来源于stack exchange,提问作者Samir Biswas
相关产品推荐
相关产品推荐

