首页 > 解决方案 > Javascript 匹配并从数组中查找

问题描述

我有一个超过 2k 的 JSON 数组

const Keyword = [
 {
        "key": "hello",
        "word": "hi. how may i help you?"
 },
{
        "key": "how are you?",
        "word": "I'm good, what about you? "
 }
]

我的话

hello , are you available right now?

现在我需要用我的词匹配并找到JSON键你好,如果匹配则返回结果真或假,

我尝试使用下面的代码

const text = "hello , are you available right now?"
if (
      Keyword.find((arr) => arr.key.toLowerCase() === text.toLowerCase()) ===
      undefined
    ) {
      return false;
    } else {
      return true;
    }

现在的问题是它找到确切的词,但我需要一个解决方案来找到匹配

谢谢

标签: javascriptnode.jsarraysjsonreactjs

解决方案


您可以在字符串上使用包含方法来检查它是否包含子字符串

const Keyword = [
 {
        "key": "hello",
        "word": "hi. how may i help you?"
 },
{
        "key": "how are you?",
        "word": "I'm good, what about you? "
 }
]

const text = "hello , are you available right now?"

const found = Keyword.find(item => text.toLowerCase().includes(item.key.toLowerCase()))
console.log(found)


推荐阅读