NodeJS 在数组中查找其属性之一包含查询文本的对象

qybjjes1  于 2023-02-21  发布在  Node.js
关注(0)|答案(2)|浏览(122)

我在js中编写了这个函数,以便从数据数组中检索对象数组,但是它没有返回数组中满足查询的所有数据
这是我的数据数组的一部分。2原来的数组包含1536个对象。

const jokes = [
    {
        "id": 1,
        "joke": "What do you call people who pretend to be Irish on St. Patrick's Day? Counterfitz"
    },
    {
        "id": 2,
        "joke": "What did one wall say to the other wall? I`ll meet you at the corner."
    },
    {
        "id": 3,
        "joke": "I thought about starting a business selling halos... ...but the cost of overheads was too high."
    },
    {
        "id": 4,
        "joke": "What happens if you pass gas in church? You have to sit in your own pew."
    },
    {
        "id": 5,
        "joke": "What's a dog's favorite mode of transportation? A waggin'"
    },
    {
        "id": 6,
        "joke": "Why couldn't the melons be together? Everyone knows melons cantaloupe."
    }
]

这是我试过的函数

const findJokes = (query) => {
    let jokesFound = jokes.filter((joke) => joke.joke.includes(query))
    return jokesFound;
}

当我查询“how”作为一个例子时,它返回了24个对象,但它应该返回132个对象。有没有更好的方法来编写这个函数?

dxxyhpgq

dxxyhpgq1#

.includes方法在搜索句子时使用严格相等,因此“How”与“How”不同。
您的代码是正确的,只是需要一个小的修改:

const findJokes = (query) => {
    let jokesFound = jokes.filter((joke) => joke.joke.toLowerCase().includes(query.toLowerCase()))
    return jokesFound;
}

有了这个,你将总是比较小写字母。

qpgpyjmq

qpgpyjmq2#

使用不区分大小写的正则表达式:

const jokes =  [{"id":1,"joke":"What do you call people who pretend to be Irish on St. Patrick's Day? Counterfitz"},{"id":2,"joke":"What did one wall say to the other wall? I`ll meet you at the corner."},{"id":3,"joke":"I thought about starting a business selling halos... ...but the cost of overheads was too high."},{"id":4,"joke":"What happens if you pass gas in church? You have to sit in your own pew."},{"id":5,"joke":"What's a dog's favorite mode of transportation? A waggin'"},{"id":6,"joke":"Why couldn't the melons be together? Everyone knows melons cantaloupe."}]

const findJokes = query => 
  jokes.filter(({joke}) => joke.match(new RegExp(query,'i')))

console.log(findJokes('DOG'))

相关问题