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

时间:2014-02-21 16:35:38

标签: javascript arrays string associative

我定义了这个结构:

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)是创建一个函数,在该结构中找到一个字符串(用户可以使用small或caps),func将有2个参数,数组本身和要查找的字符串。

任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:1)

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

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

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];
}

See demo

相关问题