質問

I have defined this structure:

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'},
};

What I need to do (with plain js) is to create a function that find a string into that structure (the user can use small or caps), the func will have 2 parameters the array itself and the string to find.

Any help will be really appreciated.

役に立ちましたか?

解決

Considering the structure of your data, it would make more sense to store the objects in an array, instead of nesting it inside an object like it is now.

That being said, you can use this function to find a string within the structure. It returns the object(s) which contains the string.

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top