【问题标题】:Javascript Match and Find from arrayJavascript 匹配并从数组中查找
【发布时间】:2021-01-18 06:39:26
【问题描述】:

我有一个超过 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 键 hello 匹配并找到我的单词,如果匹配则返回结果为真或假,

我在下面尝试了这段代码

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

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

谢谢

【问题讨论】:

  • 你的意思是includes()developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。另外,您确定要find(返回第一个匹配项)与filter(返回整组匹配项)吗?
  • 是的包含(),查找和过滤没关系我需要一个解决方案..
  • 更改:Keyword.find((arr) => arr.key.toLowerCase() === text.toLowerCase())Keyword.find((arr) =>text.toLowerCase.inculdes(arr.key.toLowerCase()))

标签: javascript node.js arrays json reactjs


【解决方案1】:

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

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)

【讨论】:

  • 我今天没有票了,但我就是这样做的。
  • const found = !!Keyword.find(item => text.toLowerCase().includes(item.key.toLowerCase())) - 用于布尔结果
【解决方案2】:

使用 RegExp 查找关键字的简单函数:

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

const findKeyword = (text) => 
  Keyword.find(r => new RegExp(r.key, 'i').test(text))

console.log(
  findKeyword("Hello, are you available right now?")
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多