有没有更好的方法用JavaScript编写此嵌套地图?

时间:2019-01-22 05:54:06

标签: javascript filter reduce

我很尴尬地发布了这篇文章,但我真的可以在这里伸出援手。这段代码看起来很讨厌。我觉得我可以使用filterreduce编写更简洁的方法,但似乎无法阻止它。有什么想法吗,社区?

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];

谢谢!

1 个答案:

答案 0 :(得分:0)

仅尝试重构您的代码:

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;