首页 > 解决方案 > 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!

标签: javascriptfilterreduce

解决方案


只是尝试重构您的代码:

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;

推荐阅读