简体   繁体   中英

Search in array javascript

I have a 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 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

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 * .

Based on your updated question, and assuming the wildcard should match numbers only, the 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 ; 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')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM