javascript - 在匹配中使用可变 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”?
解决方案
您也可以使用键引用对象。因此,在您的情况下,如果您可以调整您的searchPlant
功能以允许这样的选择器:
const searchPlants = (searchText, selector = 'Name') => {
let matches = plants.filter(plant => {
const regex = new RegExp(`^${searchText}`, 'gi');
return plant[selector].match(regex);
});
推荐阅读
- css - 将自定义 css 放入 vue.js/webpack
- c# - ASP.NET C# - 插入复合键
- python-3.x - 如何使 SSL 在 pip3 中工作?
- python - 在数据框中订购子索引并汇总前“n”个条目
- python - 远程服务器上的 nohup jupyter notebook - 关闭浏览器,输出还在吗?
- reactjs - 使用通用 Props 类型和状态类型扩展 Ract 纯组件
- python - 是否可以在 Matplotlib 中的 Slider 小部件旁边放置一个数学公式(使用 Latex)?
- php - Ajax、DOM 和提交 = 页面刷新
- c - C中的分段错误错误。代码在朋友的计算机上运行但不是我的
- html - Internet Explorer 中围绕锚点内容的焦点大纲错误