首页 > 解决方案 > 如何在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"
}

所以在我看来,我需要对函数进行可能的小改动,以便它同时搜索数组中的标签和文本字段。

标签: javascriptbixbybixbystudio

解决方案


.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));

推荐阅读