Vue.js TypeScript如何过滤对象数组获取custom_fields指定id项
Vue+TS项目订单custom_fields字段过滤失效排查
基础信息
项目基于Vue.js + TypeScript开发,使用的订单数据结构如下:
[ { "id":1, "created_at":"2019-12-06T10:22:17Z", "status":"open", "updated_at":"2020-07-27T04:21:06Z", "recipient":null, "custom_fields":[ {"id":2,"value":"ABC"}, {"id":3,"value":"EFG"}, {"id":4,"value":"CSA"} ] } ]
当前通过mapUnprinted方法做数据映射,原始方法代码如下:
private mapUnprinted (data: any) : IUnprintedSet { const result: IUnprintedSet = { orders: [], pagination: {} } if (data) { data.forEach((anUnprinted: any) => { const order: IUnprinted = { id: anUnprinted.id, created_at: anUnprinted.created_at, status: anUnprinted.status, updated_at: anUnprinted.updated_at, recipient: anUnprinted.recipient, custom_fields: anUnprinted.custom_fields // filter((item: any) => item.custom_fields.id === '3'), } result.orders!.push(order); }) result.pagination = { currentPage: data.pagination ? data.pagination.currentPage : undefined, pageSize: data.pagination ? data.pagination.pageSize : undefined, totalPages: data.pagination ? data.pagination.totalPages : undefined, totalResults: data.pagination? data.pagination.totalResults : result.orders!.length } } return result }
问题表现
需求为筛选custom_fields中id为3的对应项,两次过滤尝试均失败:
- 第一次写法:
执行后返回空数组。filter((item: any) => item.custom_fields.id === '3') - 调整路径后的第二次写法:
执行后anUnprinted.custom_fields.filter((item: any) => item.id === '3')custom_fields仍返回空数组,返回结构如下:{ "order": { "id": 1, "created_at": "2019-12-06T10:22:17Z", "status": "open", "updated_at": "2020-07-27T04:21:06Z", "recipient": null, "custom_fields": [] } }
失效原因
- 第一次写法属于对象访问路径错误:遍历
custom_fields数组时,回调参数item就是数组内的单个自定义字段对象,本身不存在custom_fields属性,访问item.custom_fields.id会拿到undefined,无法匹配到目标项。 - 第二次写法属于类型不匹配导致全等判断失效:原始数据中
custom_fields内的id字段是数字类型,但判断条件用的是字符串'3'做===全等比较,全等运算符会同时校验值和类型,数字3和字符串'3'类型不一致,因此永远无法命中匹配规则,最终返回空数组。
正确实现
将判断条件的匹配值改为和原始数据一致的数字类型即可,修正后的字段赋值代码如下:
custom_fields: anUnprinted.custom_fields.filter((item: any) => item.id === 3)
如果无法确定接口返回id的类型,也可以统一转成数字后比较,兼容字符串/数字类型的id场景:
custom_fields: anUnprinted.custom_fields.filter((item: any) => Number(item.id) === 3)
如果需求是直接拿到id为3的项的value值,而非返回数组,可以改用find方法:
// 拿到id为3的自定义字段对象,不存在时返回undefined const targetField = anUnprinted.custom_fields.find((item: any) => item.id === 3) // 取对应value const targetValue = targetField?.value
内容的提问来源于stack exchange,提问作者tedeeee
相关产品推荐
相关产品推荐

