簡體   English   中英

有沒有更好的方法用JavaScript編寫此嵌套地圖?

[英]Is there a better way to write this nested map in JavaScript?

我不好意思發表這個,但是我真的可以在這里幫忙。 這段代碼看起來很討厭。 我覺得我可以使用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];

謝謝!

只是嘗試重構您的代碼:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM