javascript - Is there a better way to write this nested map in JavaScript?
问题描述
I'm embarrassed to post this but I could really use a hand here. This code just looks nasty. I have a feeling that I can write a cleaner approach with filter
or reduce
but can't seem to stab it. Any thoughts, community?
const vin = detections.map(detection => {
return detection.textAnnotations.map(v => {
let n = v.description.replace(/\s+/g, '');
if (n.length === 17) {
return n;
}
});
})[0][0];
Thanks!
解决方案
只是尝试重构您的代码:
const getMatchedTextAnnotation = (textAnnotation) => {
const n = textAnnotation.description.replace(/\s+/g, '');
return n.length === 17 ? n : null;
}
const extractAnnotationsFromDetection = (detection) => {
return detection.textAnnotations.reduce((arr, textAnnotation) => {
const n = getMatchedTextAnnotation(textAnnotation);
return !!n ? [ ...arr, n] : arr;
}, [])
}
const vinArr = detections.reduce((arr, detection) => {
const subArr = extractAnnotationsFromDetection(detection);
return !!subArr ? [ ...arr, ...subArr ] : arr;
}, [])
const vin = !!vinArr ? vinArr[0] : null;
推荐阅读
- java - 为什么在成功的 Firebase 登录之前调用另一个活动中的方法?
- docker - Docker 容器无法访问本地托管在 mac 上的 Tomcat
- node.js - 不能在heroku中使用fs
- javascript - 比较不同的日期格式
- ios - AVAggregateAssetDownloadTask 似乎加载了两次 m3u8 文件
- windows - 安装 PyCharm 专业版 2019.3 后“缺少必要的插件:Pythonid”
- html - 更改下一个和后退按钮之间的间距
- c++ - C++ / 错误:表达式必须具有整数或无范围枚举类型
- javascript - javascript中的全局标志
- c# - 处理来自单例对象的具体事件