javascript - 如何仅读取特定类型的 API 数据?
问题描述
我的脚本从网站 API ( https://api.discogs.com/ )读取数据,例如https://api.discogs.com/releases/249504
"identifiers": [{"type": "Barcode", "value": "5012394144777"}...]
我希望它只读取条形码类型的标识符。现在我可以看到它正在读取整个数组,这不是我想要的;这是“撒网太宽”/
var barcode = data.identifiers;
const barcode = data.identifiers || []
const barcode = data.identifiers.type == "Barcode" || []
我认为这是一个对象数组,但是我如何只针对我想要的数据呢?TIA。
编辑:我很确定“条形码”将作为带引号的字符串输入,因为其他可能的标识符类型之一是“标签代码”,它肯定必须作为字符串输入,因为它包含一个空格!
解决方案
我认为您正在寻找过滤器功能:
> data = [{'type':'Barcode', value:'A'}, {'type':'Matrix', 'value':'B'}]
[ { type: 'Barcode', value: 'A' }, { type: 'Matrix', value: 'B' } ]
> data.filter(x => x.type == 'Barcode')
[ { type: 'Barcode', value: 'A' } ]
如果你不知道内置的过滤器方法,你也可以用 for 循环做这样的事情:
const b = []
for (x of data) {
if (x.type == 'Barcode') {
b.push(x)
}
}
推荐阅读
- r - 考虑插入符号中的技术复制
- spring-boot - 如何在spring boot中以dd-mm-yyy格式插入日期
- laravel-8 - API 端点是否可以返回多个模型(例如在前端配置创建/更新表单时)?
- java - Groovy - java同时进行多个转换
- flutter - 从后代小部件调用函数以触发滚动控制器
- microsoft-graph-api - 使用 Graph API 进行 SharePoint 备份
- reactjs - hasura graphql 查询中的特殊字符
- c++ - 模板中的 C++ 双链表
- python - 如何使用 plotly_express 创建线图,其中可以通过下拉菜单选择 pandas 数据框?
- javascript - 不设置最大日期角度js