首页 > 解决方案 > 在匹配中使用可变 JSON 名称(正则表达式)

问题描述

我正在创建一个 webapp,它允许用户搜索包含多个名称-数据对的 JSON 文件。我正在使用 fetch 获取 JSON 数据,然后对其进行过滤(请参见下面的代码)。

JSON 数据如下所示:

 {

    "Name": "Abelia grandiflora",

    "Cultivar": "cv. Edward Goucher",

    "Type": "Softwood, terminal or subterminal",

    "Stage": "n/a",

    "Taken": "July",

    "Medium": "Perlite or well drained medium",

    "Auxin": "Hormex - full strength",

    "Structure": "mist",

    "Heat": "No Bottom Heat .",

    "Percent": "100%",

    "Time": "4 weeks",

    "Care": "n/a",

    "Location": "Honolulu, Hawaii.",

    "Reference": "Oka, P. 1978. Propagation of Abelia grandiflora Edward Goucher. The Pl. Prop. 24(1):4-5."

  }

要检索 JSON 数据:

const getPlants = async () => {
     const res = await fetch('data/plants.json');
     plants = await res.json();
};

根据用户文本输入过滤数据:

const searchPlants = searchText => {

     let matches = plants.filter(plant => {

     const regex = new RegExp(`^${searchText}`, 'gi');

     return plant.Name.match(regex);

});

“返回植物.Name.match(regex);”中的“名称” 表达式是我想要变量。我希望它可以通过用户输入进行更改。例如,JSON 数据具有名称-数据对,其中包括“名称”(如上)以及“栽培品种”和“参考”。如果用户选择基于“Cultivar”或“Reference”进行搜索,如何将return语句中的“Name”替换为“Cultivar”或“Reference”?

标签: javascript

解决方案


您也可以使用键引用对象。因此,在您的情况下,如果您可以调整您的searchPlant功能以允许这样的选择器:

const searchPlants = (searchText, selector = 'Name') => {

     let matches = plants.filter(plant => {

     const regex = new RegExp(`^${searchText}`, 'gi');

     return plant[selector].match(regex);

});

推荐阅读