【问题标题】:Is there a better way to write this nested map in JavaScript?有没有更好的方法来用 JavaScript 编写这个嵌套映射?
【发布时间】:2019-06-15 13:19:11
【问题描述】:

我很尴尬地发布这个,但我真的可以在这里使用。这段代码看起来很糟糕。我有一种感觉,我可以用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];

谢谢!

【问题讨论】:

  • 好吧,对于初学者来说,不要不好意思发布代码,否则您将无法通过社区的投入来改进!
  • 为什么是两个.maps?为什么不直接选择其中的第一个detection 和第一个textAnnotations,然后适当替换,完全不循环?
  • @NikKyriakides 实际上,即使在 CR:codereview.stackexchange.com/help/dont-askcodereview.stackexchange.com/help/on-topic,也不应该问这个问题。它没有勾选大多数方框。但是好吧,让 OP 在那里问它,让我们看看会发生什么......
  • @GerardoFurtado 我坚持

标签: javascript filter reduce


【解决方案1】:

只是尝试重构您的代码:

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;

【讨论】:

  • 我不明白这如何使它变得更好。
猜你喜欢
  • 2022-01-10
  • 2022-06-19
  • 2017-11-06
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
相关资源
最近更新 更多