javascript - 如何在json数组中搜索文本
问题描述
需要在 JSON 数组中搜索文本字符串。
Bixby 中的事实/笑话模块目前按标签而不是全文搜索。我想修改过滤功能来搜索全文字段。
目前,过滤器功能是这样的。
exports.findContentJS = findContentJS
function findContentJS (items, searchTerm) {
var matches = items.filter(function (x) {
if (x.tags) {
// Filter on filter
var matchTag = x.tags.filter(function (y) {
return y == searchTerm
});
return (matchTag != "");
}
});
return matches;
}
我尝试将“标签”更改为“文本”。
因此,对于“马克吐温”的搜索,我收到如下错误消息:
类型错误:在对象中找不到函数过滤器 银行家是这样的人,他在阳光明媚的时候借给你他的雨伞,并在开始下雨的那一刻想要回来。资料来源:马克吐温
这是json文件中对应的对象:
{
tags: ["literature"],
text: "A banker is a fellow who lends you his umbrella when the sun is shining and wants it back the minute it begins to rain. Source: Mark Twain"
}
所以在我看来,我需要对函数进行可能的小改动,以便它同时搜索数组中的标签和文本字段。
解决方案
.text 不是数组,所以不会有过滤功能
只需使用
exports.findContentJS = findContentJS
function findContentJS (items, searchTerm) {
var matches = items.filter(function (x) {
return x.includes(searchTerm);
});
return matches;
}
或者,
exports.findContentJS = findContentJS
const findContentJS = (items, searchTerm) => items.filter(x => x.includes(searchTerm));
推荐阅读
- python - Python Flask 区块链给出“'dict' object not callable”
- javascript - Nodejs Promise.All 带有承诺链?
- python - 如何找到年龄之间的男性数量
- php - 表单未将数据发布到数据库中
- reporting-services - Google Cloud 存储桶外部图像未在 SSRS 中显示
- javascript - 在父按钮单击时调用并执行多个子函数
- .net-core - ASP.NET Core 2.1 - 与依赖注入相关的堆栈溢出异常
- c++ - C++ - 线程池
- c++ - 从 C++17 中的另一个构造函数调用具有不同参数类型的构造函数
- twitter-bootstrap - 在 Bootstrap 4 中使字体变大的问题