我正在创建一个 Web 应用程序,允许用户搜索包含多个名称-数据对的 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);
});
“名称”中的“return plant.Name.match(regex);”表达式是我想要的变量。我希望它可以根据用户输入进行更改。例如,JSON 数据具有名称-数据对,其中包括“名称”(如上所述)以及“品种”和“引用”。如果用户选择根据“Cultivar”或“Reference”进行搜索,如何将返回语句中的“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);
});
关于javascript - 在匹配(正则表达式)中使用变量 JSON 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58575674/