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

2

I would like to look up the word "script" inside an object, which would be the Roteiro variable.

I started trying to figure something out after searching the internet, but I got lost, and it did not work, so I need help with the reasoning ... 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 get the "location" where the word was found, is it possible?

    
asked by anonymous 12.02.2015 / 20:03

2 answers

2

If you do not know the depth of this object it is best to use a recurring function of type:

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 property of the object, iterating sub-objects / sub-arrays by calling itself again, and returns an array with the sub-object and the key containing the searched string.

Example: link
which gives an array with the object and key: [Object, "descricaoRoteiro"]

    
12.02.2015 / 23:40
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);

See that JSFIDDLE

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

    
12.02.2015 / 20:45