Search in array javascript -
i have json array:
var arr = [ { "path": "a/b/c/*", "id": "1" }, { "path": "l/m/*/n", "id": "2" }, { "path": "a/b/c/d/*", "id": "3" } ]
i want id of element matches input param, if pass input string , array should 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 want * wildcard while search. have struggled lot while implementing this, appreciated.
convert each path
regular expression, noting regular expression wildcard .*
instead of *
.
based on updated question, , assuming wildcard should match numbers only, regular expression becomes [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 ; < arr.length ; i++) { //iterate through array re = new regexp(arr[i].path.replace(/\*/g, '[0-9]+')); //convert path regexp if(re.test(input)) { //test 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));
Comments
Post a Comment