搜索Json数组

时间:2014-12-12 14:46:28

标签: javascript arrays regex json

我有一个像下面这样的json数组:

[
    {"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":""}
]

我想在这个json数组中搜索特定的标题。但问题是,我想用正则表达式进行搜索。 例如:sb搜索“ad” - >该函数应返回前两个json字符串(Adjust和Adn)。

我不知道,现在要设置一个可以实现此功能的javascript函数。

一些想法?

3 个答案:

答案 0 :(得分:5)

试试这个:

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.
});

结果:

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

如果您只想要一个标题数组,那么您可以映射结果,如下所示:

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

标题

["Adjust", "Adn"]

为了提高效率,您希望在过滤数组后进行映射。这样您只需迭代过滤后的结果,而不是首先遍历所有项目以获取标题,然后再次迭代所有来过滤它们

当然,这可以与过滤结合使用:

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

请注意,Array.prototype.filter()Array.prototype.map()在IE 8或更低版本中不受支持。但是,我链接的页面确实有一些polyfill,以使这些功能在旧版本的IE中工作。

答案 1 :(得分:3)

这是一个原生对象。你可以这样做,首先使用Array.map创建一个标题数组,然后使用Array.filter过滤它们

var titles = obj.filter(function(o){
   return /^ad/i.test(o.title);
}).map(function(o){ return o.title; });

答案 2 :(得分:2)

Amit Joki的回答是 的回答 如果你不想使用map(),你也可以尝试:

var json = [
    {"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":""}
];

function search(array, re) {
    var regexp = new RegExp(re, 'gi');
    for (var i = 0; i < array.length; i++) {
        return array[i].title.match(regexp);
    }
    throw "Couldn't find object like " + re;
}

console.info(search(json, 'ad'));