Insert into array, whose parent property value is equal to the property value of the child object

Asked

Viewed 70 times

5

I have an object (Questions) and I want another object (Answers) to be added to it according to a common id.

var Perguntas = [
    { idPergunta: 13, textoPergunta: "Qual seu nome" , Respostas : [] },
    { idPergunta: 26, textoPergunta: "Qual sua idade" , Respostas : [] }        
]

var Respostas = [
    { idPergunta: 13, idResposta: 1, textoResposta: "Joao", ordemResposta: 0 },
    { idPergunta: 13, idResposta: 2, textoResposta: "Jose", ordemResposta: 1 } 
    { idPergunta: 26, idResposta: 3, textoResposta: "15", ordemResposta: 0 },
    { idPergunta: 26, idResposta: 4, textoResposta: "30", ordemResposta: 1} 
]

for(var i = 0; i < Respostas.length; i++){
    Pergunta[?].Respostas = Respostas[i];
}
// Quero evoluir esse código pra chegar a resposta.

I broke my head, but I still can not think of an algorithm to solve this, maybe it is simple and a push will help me.

This code I made in my head without testing, if you notice any syntax error let me know I fix it. I do not know for example if I can declare Answers: [] inside Questions or if it is just leave empty, null or not put.

1 answer

7


You can do it like this:

Perguntas.forEach(function (pergunta) {
    var id = pergunta.idPergunta;
    pergunta.Respostas = Respostas.filter(function (resposta) {
        return resposta.idPergunta == id; // aqui o filter retira as que derem false
    });
});

Example: http://jsfiddle.net/j0fLLLm7/1

var Perguntas = [
    { idPergunta: 13, textoPergunta: "Qual seu nome" , Respostas : [] },
    { idPergunta: 26, textoPergunta: "Qual sua idade" , Respostas : [] }        
]

var Respostas = [
    { idPergunta: 13, idResposta: 1, textoResposta: "Joao", ordemResposta: 0 },
    { idPergunta: 13, idResposta: 2, textoResposta: "Jose", ordemResposta: 1 },
    { idPergunta: 26, idResposta: 3, textoResposta: "15", ordemResposta: 0 },
    { idPergunta: 26, idResposta: 4, textoResposta: "30", ordemResposta: 1} 
]

Perguntas.forEach(function (pergunta) {
    var id = pergunta.idPergunta;
    pergunta.Respostas = Respostas.filter(function (resposta) {
        return resposta.idPergunta == id;
    });
});

alert(JSON.stringify(Perguntas[0], null, 2));

The idea is to iterate all questions and on the property pergunta.Respostas go get the answers. Here .filter() is very practical because it checks all the answers and leaves an array only with those who have the id same as the question (resposta.idPergunta == id;).

  • 1

    Perfect, exactly what I wanted and with little code.

  • @Joaopaulo ótimo!

Browser other questions tagged

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