JavaScript匹配数组ID与对象fraud_type_id并返回键名排错
问题背景
现有如下数据结构:
const report = { fraud_ids: [2, 3, 4, 15], } const fraudTypes = { ACH: { fraud_category: "fraud", fraud_subcategory: "a", fraud_type_id: "4", }, 'Account takeover': { fraud_category: "misc", fraud_subcategory: "a", fraud_type_id: "2", }, 'Advance fee': { fraud_category: "fraud", fraud_subcategory: "b", fraud_type_id: "8", }, 'Against Financial Institution Customer(s)': { fraud_category: "cyber", fraud_subcategory: "b", fraud_type_id: "15", }, 'Against Financial Institution(s)': { fraud_category: "cyber", fraud_subcategory: "a", fraud_type_id: "78", }, 'Alters or cancels transaction to avoid BSA recordkeeping requirement': { fraud_category: "structuring", fraud_subcategory: "a", fraud_type_id: "3", }, }
需求:通过fraud_type_id字段,将fraudTypes与fraud_ids数组中的ID做匹配,匹配成功后返回fraudTypes对应的键名,按fraud_ids的顺序排列。
以上述示例数据为例,预期返回结果为:
['Account takeover', 'Alters or cancels transaction to avoid BSA recordkeeping requirement', 'ACH', 'Against Financial Institution Customer(s)']
原实现代码运行后得到包含4个undefined的数组,不符合预期,原代码如下:
const x = report.fraud_ids.map(id => { Object.keys(fraudTypes).map(fraudDescription => { if (parseInt(fraudTypes[fraudDescription].fraud_type_id, 10) === id) { return true; } }); });
原代码存在的问题
- 外层
map的回调函数没有写返回值:箭头函数如果用大括号包裹代码块,必须手动写return才能返回内容,原代码里只执行了内层遍历逻辑,没有返回任何值,因此外层map每一项默认返回undefined,最终得到全是undefined的数组。 - 方法选用错误:内层遍历的目的是找到第一个匹配的键,不需要返回和遍历长度一致的数组,用
map会遍历所有键,最终得到一个混杂undefined和匹配值的数组,这种场景用find更合适,找到匹配项就会停止遍历。 - 匹配后的返回值错误:就算补全返回逻辑,原代码匹配成功后只返回了
true,没有返回实际需要的键名字符串。
修正后的实现
const x = report.fraud_ids.map(id => { // 查找fraud_type_id和当前id相等的键名 return Object.keys(fraudTypes).find(fraudDescription => { return parseInt(fraudTypes[fraudDescription].fraud_type_id, 10) === id }) })
运行上述代码即可得到和预期一致的返回结果。
内容的提问来源于stack exchange,提问作者London804
相关产品推荐
相关产品推荐

