[英]Search in array javascript
I have a json array: 我有一个json数组:
var arr =
[
{
"path": "a/b/c/*",
"id": "1"
},
{
"path": "l/m/*/n",
"id": "2"
},
{
"path": "a/b/c/d/*",
"id": "3"
}
]
I want the id of the element which matches the input param, like if I pass a input string and the array I should get the id 我想要与输入参数匹配的元素的ID,就像我传递输入字符串和数组一样,我应该获得ID
foo(input,arr);
so 所以
var input = 'a/b/c/5'; //or input = 'a/b/c/4';
foo(input,arr) // should return 1
similarly 类似地
var input = 'l/m/78/n';
foo(input,arr); // should return 2
similarly 类似地
var input = 'a/b/c/d/1';
foo(input,arr); // should return 3
So I want * to be the wildcard while search. 因此,我希望*在搜索时成为通配符。 I have struggled a lot while implementing this, any help will be appreciated. 在实施此功能时,我付出了很多努力,任何帮助将不胜感激。
Convert each path
into a regular expression , noting that the regular expression for a wildcard is .*
instead of *
. 将每个path
转换为正则表达式 ,请注意,通配符的正则表达式是.*
而不是*
。
Based on your updated question, and assuming the wildcard should match numbers only, the regular expression becomes [0-9]+
: 根据您更新的问题,并假设通配符应仅与数字匹配,则正则表达式变为[0-9]+
:
var arr = [{"path": "a/b/c/*","id": "1"}, {"path": "l/m/*/n","id": "2"}, {"path": "a/b/c/d/*","id": "3"} ]; function foo(input, arr) { var i, RE; for(i = 0 ; i < arr.length ; i++) { //iterate through the array RE = new RegExp(arr[i].path.replace(/\\*/g, '[0-9]+')); //convert path to regexp if(RE.test(input)) { //test for a match return arr[i].id; } } } console.log(foo('a/b/c/5', arr)); console.log(foo('l/m/78/n', arr)); console.log(foo('a/b/c/d/1', arr));
function foo(input,arr){ for(var i in arr){ var re = new RegExp(arr[i].path.replace(/\\*/g, '.*')); if (re.test(input)) { return arr[i].id; } } return null; } var arr = [ { "path": "a/b/c/*", "id": "1" }, { "path": "l/m/*/n", "id": "2" } ]; document.write(foo("l/m/1/n",arr));
Here is a regex free version: 这是一个正则表达式免费版本:
var arr = [{ 'path' : 'a/b/c/*', 'id' : '1' }, { 'path' : 'l/m/*/n', 'id' : '2' } ] function search(arr, input) { input = input.split('/'); return arr.filter(function (el) { var value = el.path.replace('*', '').split('/'); var passed = true; for (var i = 0; i < value.length; i++) { if (input[i].length < 1 || value[i].length < 1 || input[i] == value[i]) {} else { passed = false; } } return passed; }) } console.log(search(arr, 'a/b/c/5')); console.log(search(arr, 'l/m/78/n'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.