How to search for a string inside an object in an array?

Asked

Viewed 2,503 times

2

I would like to search for the word "script" within an object, which would be the variable Roteiro.

I started trying to figure something out after searching the Internet, but I got lost, and it didn’t work, so I need help with the thinking... as follows:

var Roteiro = {};
var roteiro = [{ descricaoRoteiro: "Descrição roteiro", idRoteiro: 1 }];
var perguntas = [{ tituloPergunta: "Titulo pergunta", idPergunta: 2 }];
var opcoes = [{ tituloOpcao: "Titulo opcao roteiro", idOpcao: 3 }];
Roteiro = { roteiro: roteiro, perguntas: perguntas, opcoes: opcoes};

for (var key in Roteiro) { 
    debugger;
    if(typeof(Roteiro[key]) == "object"){
        for (var key2 in Roteiro[key]){
            for (var key3 in Roteiro[key][key2]){
                for (var name in Roteiro[key][key2][key3].keys){
                    alert(Roteiro[key][key2][key3]
                };
            }
        }
    }
}

After finding some record I would like to pick up the "place" where the word was found, it is possible?

  • I’m not very good at javascript, but wouldn’t I have an easier way using recursion? something like... Gist Link

  • The two answers return the first occurrence found. This is what you need, or you would need to return all?

2 answers

2

See if this solution suits you:

var resultSearch = [];

    for (var key in Roteiro) {

        Roteiro[key].forEach(function(value, key){

            for (k in value) {
                if (/roteiro/g.test(value[k])) {
                    resultSearch.push(value);
                }

            }
        });

    }

console.log(resultSearch);

Look at this one JSFIDDLE

Verification is done through a regular expression, where /roteiro/g.test evaluates whether the current value of the loop contains the word "script". Thus, if true, the method push adds the value in a new Array, which is our variable resultSearch.

  • 2

    Alternative option: indexOf instead of regular expression.

  • Improvements are always welcome, friend @bfavaretto

2


If you don’t know the depth that object is best to use a recurring function like:

function procurar(obj, agulha) {
    var chaves = Object.keys(obj);
    for (var i = 0; i < chaves.length; i++) {
        var chave = chaves[i];
        if (!obj[chave]) continue;
        else if (typeof obj[chave] == 'object') return procurar(obj[chave], agulha);
        else if (obj[chave].indexOf(agulha) != -1) return [obj, chave];
    }
    return false;
}

This function "scans" each object property, iterating sub-objects/sub-arrays calling itself again, and returns an array with the sub-object and the key containing the string (needle) sought.

Example: http://jsfiddle.net/se93yyj7/
which gives an array with the object and key: [Object, "descricaoRoteiro"]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.