简体   繁体   English

在资源数组中找到合适的动态路径资源的最佳方法是什么?

[英]What is the best way to find the proper dynamic path resource into an array of resources?

I have the following Array of resources, including a dynamic resource ("guides/:guideId/packages") and a currentURL (guides/GUIDE007/packages):我有以下资源数组,包括一个动态资源(“guides/:guideId/packages”)和一个 currentURL(guides/GUIDE007/packages):

const resources = ["guides", "guides/files", "guides/:guideId/packages"];
const currentURL = "guides/GUIDE007/packages";

const getResourceMatch = (resources, currentURL) => { return ... ?? }  

const resourceMatch = getResourceMatch(resources, currentURL);
console.log(resourceMatch) // guides/:guideId/packages

What can be the best way to find that format match into the array as the currentURL matches a resource or a resource format?当 currentURL 匹配资源或资源格式时,找到该格式匹配到数组中的最佳方法是什么?

I will preface this by saying you should probably try to find a library that can do route matching for you.我会先说您应该尝试找到一个可以为您进行路由匹配的库。 Nevertheless, here's a route matching implementation for you that turns your resource strings into regular expressions to test the currentURL against.不过,这里有一个路由匹配实现,它将您的资源字符串转换为正则表达式以测试 currentURL。

 const resources = ["guides", "guides/files", "guides/:guideId/packages", "guides/packages/:packageId"]; const currentURL1 = "guides/GUIDE007/packages"; const currentURL2 = "guides/packages/PKG007"; const getResourceMatch = (resources, currentURL) => { return resources.find(r => { const regexStr = '^' + r.replace(/(:\\w+)/g,'[\\\\w-]+') + '$'; const regex = new RegExp(regexStr); return regex.test(currentURL); }) } const resourceMatch1 = getResourceMatch(resources, currentURL1); const resourceMatch2 = getResourceMatch(resources, currentURL2); console.log(resourceMatch1) // guides/:guideId/packages console.log(resourceMatch2) // guides/packages/:packageId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在数组中查找元素的最佳方法是什么? - What is the best way to find element in an Array? 在 js 中从另一个数组中的数组中查找元素的最佳方法是什么? - What is the best way to find elements from an array in another array in js? 在二维数组中找到最短数组的最佳方法是什么? - What's the best way to find the shortest array in a two dimensional array? 在javascript中搜索对象数组以查找另一个数组的最佳方法是什么? - What is the best way to search an array of objects to find another array in javascript? 从对象数组中查找对象索引的最佳方法是什么 - javascript - What is the best way to find index of object from array of objects - javascript 找到开始时间和结束时间之间的时间间隔的最佳方法是什么 - What is the best way to find the intervals between the array of start and end time 在数组中找到最后一个非空值的最佳方法是什么 - What's the best way to find the last non empty value in array 在数组中找到事件 x 和事件 y 的最佳方法是什么? - What would be the best way to find an event x and an event y in an array? 在对象数组中查找完全相同对象的索引的最佳方法(键是动态的) - Best way to find index of exact same object in object Array (key is dynamic) 重置动态对象值的最佳方法是什么 - What is best way to reset values of a dynamic object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM