如何在Google Spreadsheet API请求中过滤数据,或对返回数组过滤?
方案1:API请求阶段直接过滤(推荐)
你当前使用的Google Sheets Data API v3原生支持通过sq查询参数实现类SQL的条件过滤,无需拉取全量数据,可大幅减少不必要的传输量。
你需要在原请求URL后添加sq参数,过滤条件按照你要求的category == 'football'写法对应为sq=category='football',注意参数需要做URL编码,修改后的代码如下:
created(){ // sq参数已做URL编码,避免特殊字符解析出错 this.axios.get("https://spreadsheets.google.com/feeds/list/my-id/1/public/full?alt=json&sq=category%3D%27football%27") .then(response => (this.items = response.data.feed.entry)) },
如果需要多条件过滤,直接按照SQL语法拼接即可,比如同时过滤category为football、year大于2020的行,sq参数写为category='football' and year>2020后做URL编码即可。
方案2:返回数据后本地过滤
如果无法调整API请求逻辑,直接对返回的数组做filter过滤即可。注意Google Sheets API返回的自定义列字段都会放在gsx$前缀的属性下,列名会自动转成全小写且去除空格,字段值存在$t属性中,对应代码如下:
created(){ this.axios.get("https://spreadsheets.google.com/feeds/list/my-id/1/public/full?alt=json") .then(response => { // 过滤category为football的行 this.items = response.data.feed.entry.filter(item => { return item.gsx$category?.$t === 'football' }) }) },
注意:如果你的表格列名不是全小写的
category,比如是Category或者带空格的Category Name,可以先打印response.data.feed.entry[0]查看对应列的实际gsx$开头的字段名,替换示例中的gsx$category即可。
内容的提问来源于stack exchange,提问作者Antoine Kurka
相关产品推荐
相关产品推荐

