Abhijeet Abhijeet - 4 months ago 7
JSON Question

Search in array javascript

I have a json array:

var arr =
[
{
"path": "a/b/c/*",
"id": "1"
},
{
"path": "l/m/*/n",
"id": "2"
}
]


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


So I want * to be the wildcard while search.
I have struggled a lot while implementing this, any help will be appreciated.

Answer

Convert each path into a regular expression, noting that the regular expression for a wildcard is .* instead of *:

var arr =  [{"path": "a/b/c/*","id": "1"},{"path": "l/m/*/n","id": "2"}];

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, '.*')); //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));

Comments