Javascript:在对象列表中查找字符串

Lowtrux

我已经定义了这种结构:

var game_list = { 
    1: {name:'Vampires hunter', description:'The best vampires game in the world'},
    2: {name:'Christmas vampires', description:'The best vampires game in the world'},
    3: {name:'Fruit hunter', description:'The best vampires game in the world'},
    4: {name:'The fruitis', description:'The best vampires game in the world'},
    5: {name:'james bond', description:'The best vampires game in the world'},
    6: {name:'Vampires hunter', description:'The best vampires game in the world'},
};

我需要做的(使用普通js)是创建一个在该结构中查找字符串的函数(用户可以使用小写或大写),该func将具有2个参数,数组本身和要查找的字符串。

任何帮助将不胜感激。

列维

考虑到数据的结构,将对象存储在数组中而不是像现在这样将其嵌套在对象中会更有意义。

话虽如此,您可以使用此函数在结构中查找字符串。它返回包含字符串的对象。

function findString(obj, str) {
    str = str.toLowerCase();
    var results = [];
    for(var elm in obj) {
        if(!obj.hasOwnProperty(elm)){
            continue;
        }
        for (var key in obj[elm]) {
            if (obj[elm].hasOwnProperty(key) && obj[elm][key].toString().toLowerCase().indexOf(str) > -1) {
                results.push(obj[elm]);
            }
        }
    }
    return results.length > 1 ? results : results[0];
}

观看演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章