首页 > 解决方案 > 如何仅读取特定类型的 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。

编辑:我很确定“条形码”将作为带引号的字符串输入,因为其他可能的标识符类型之一是“标签代码”,它肯定必须作为字符串输入,因为它包含一个空格!

标签: javascript

解决方案


我认为您正在寻找过滤器功能:

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

推荐阅读