基于标签JavaScript数组的自动完成

发布于 2025-02-13 08:04:18 字数 666 浏览 0 评论 0原文

我正在尝试创建一个普通的JavaScript函数,该功能将用户输入与一系列标签进行比较并返回最佳匹配。我已经创建了这样的JSON索引:

[
    {
        "data-governance": {
            "tags": ["data", "governance"],
            "href": "data-governance.html"
        }
    },
    {
        "data-quality": {
            "tags": ["data", "quality"],
            "href": "data-quality.html"
        }
    }
]

我希望该函数的行为如下:如果用户输入“ data”它应该返回 data-Governance 和< em>数据质量 href属性。但是,如果用户输入“ Data Gov”应该返回 data-covernance href属性。

我发现了一些示例,其中使用REGEX中的字符串匹配完成了自动完成,但是没有比较字符串数组(即标签)。

希望有人可以将我指向正确的方向。

I am trying to create a plain JavaScript function that compares user input against an array of tags and returns the best match. I have created a JSON index like this:

[
    {
        "data-governance": {
            "tags": ["data", "governance"],
            "href": "data-governance.html"
        }
    },
    {
        "data-quality": {
            "tags": ["data", "quality"],
            "href": "data-quality.html"
        }
    }
]

I would like the function to behave as follows: if the user inputs "data" it should return both the data-governance and data-quality href attributes. However, if the user inputs "data gov" it should return the data-governance href attribute only.

I have found a few examples where autocompletion is done using string matching in RegEx, but none comparing an array of strings (i.e., tags).

Hopefully someone can point me into the right direction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

客…行舟 2025-02-20 08:04:18

你可以做这样的事情,

const data = [
   {
      'data-governance': {
          tags: ['data', 'governance'],
          href: 'data-governance.html',
       },
   },
   {
      'data-quality': {
         tags: ['data', 'quality'],
         href: 'data-quality.html',
      },
   },
];

const findMatches = (items, tag) => {
  return items
     .filter((item) => {
        const { tags } = Object.values(item)[0];
        return tags.includes(tag);
     })
     .map((item) => Object.keys(item)[0]);
};

console.log(findMatches(data, "data"));

You can do something like this,

const data = [
   {
      'data-governance': {
          tags: ['data', 'governance'],
          href: 'data-governance.html',
       },
   },
   {
      'data-quality': {
         tags: ['data', 'quality'],
         href: 'data-quality.html',
      },
   },
];

const findMatches = (items, tag) => {
  return items
     .filter((item) => {
        const { tags } = Object.values(item)[0];
        return tags.includes(tag);
     })
     .map((item) => Object.keys(item)[0]);
};

console.log(findMatches(data, "data"));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文