简体   繁体   English

有没有更好的方法用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. 我觉得我可以使用filterreduce编写更简洁的方法,但似乎无法刺穿它。 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! 谢谢!

Just an attempt to refactor your code: 只是尝试重构您的代码:

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