Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Json Array

I got a json array like below:

[
    {"value":"uk-icon-adjust","title":"Adjust","url":"#", "text":""},
    {"value":"uk-icon-adn","title":"Adn","url":"#", "text":""},
    {"value":"uk-icon-align-center","title":"Align center","url":"#", "text":""},
    {"value":"uk-icon-align-justify","title":"Align justify","url":"#", "text":""},
    {"value":"uk-icon-align-left","title":"Align left","url":"#", "text":""}
]

I want to search this json array for specific titles. But the problem is, that I want to search with a Regex. e.g: sb searchs for "ad" -> the function should return the first two json strings (Adjust and Adn).

I have no idea, now to setup a javascript function which can achieve this.

Some ideas?

like image 572
Smeaven Avatar asked Sep 16 '25 11:09

Smeaven


2 Answers

Try this:

var array = [
    {"value":"uk-icon-adjust","title":"Adjust","url":"#", "text":""},
    {"value":"uk-icon-adn","title":"Adn","url":"#", "text":""},
    {"value":"uk-icon-align-center","title":"Align center","url":"#", "text":""},
    {"value":"uk-icon-align-justify","title":"Align justify","url":"#", "text":""},
    {"value":"uk-icon-align-left","title":"Align left","url":"#", "text":""}
  ],
  searchString = 'ad',
  searchRegExp = new RegExp(searchString , 'i'); // 'i' makes the RegExp ignore case

var result = array.filter(function(e){ // Filter out any items that don't pass the
    return searchRegExp.test(e.title); //  RegExp test.
});

Result:

[
    {"value":"uk-icon-adjust","title":"Adjust","url":"#","text":""},
    {"value":"uk-icon-adn","title":"Adn","url":"#","text":""}
]

If you only want an array of titles, you can then map the result, like this:

var titles = result.map(function(e){
    return e.title;
});

Titles:

["Adjust", "Adn"]

You'll want to do this mapping after filtering the array, for efficiency. This way you'll only have to iterate over the filtered result, instead of first iterating over all items to get the titles, then iterating over all of them again to filter them.

Of course, this can be combined with the filtering:

var result = array.filter(function(e){
    return searchRegExp.test(e.title);
}).map(function(e){
    return e.title;
});

Please keep in mind that both Array.prototype.filter() as Array.prototype.map() Aren't supported in IE 8 or lower. However, the pages I linked to do have some polyfills to make these functions work in older versions of IE.

like image 101
Cerbrus Avatar answered Sep 19 '25 01:09

Cerbrus


That's an native Object. You can do it this way though, by first creating an Array of titles by using Array.map and then filter them using Array.filter

var titles = obj.filter(function(o){
   return /^ad/i.test(o.title);
}).map(function(o){ return o.title; });
like image 45
Amit Joki Avatar answered Sep 18 '25 23:09

Amit Joki