How to print a JSON array?

Asked

Viewed 517 times

0

var listaNomeProjeto =
    [{
        "nomeProjeto": "NomeProjeto1",
        "subProjeto": [
                "Sub Projeto1",
                "Sub Projeto2",
                "Sub Projeto3",
                "Sub Projeto4",
                "Sub Projeto5",
                "Sub Projeto6",
                "Sub Projeto7"
            ]
    },{
        "nomeProjeto": "NomeProjeto2",
        "subProjeto": [
            "Sub Projeto1",
            "Sub Projeto2",
            "Sub Projeto3",
            "Sub Projeto4"
        ]
    }];

Trying to print with repeat loop: - No $(this).val() the value of a select box is received.

    for( var i = 0; i< listaNomeProjeto.length; i++){
        if(listaNomeProjeto[i].nomeProjeto === $(this).val()){
            console.log(listaNomeProjeto[i].subProjeto[0]);

        }
    }

I do a search on nomeProjeto, if I find the name I have to print all the content inside the subProjeto. I must make one more loop to traverse the array inside the subProjeto? Could you help me?

1 answer

2


I will suggest a different solution without using loops. First Filtre by what you are looking for with the method filter:

listaFiltrada = listaNomeProjeto.filter(function(e) {
    return e.nomeProjeto === 'NomeProjeto2'
});

This list contains only the projects you are looking for. Within the function you define the criteria to filter the results. Now let’s turn the list, to get the information you want, with the method map:

subProjs = listaFiltrada.map(function(e) { return e.subProjeto; });

To display the list of subprojects, foreach:

subProjs.forEach(function(e){ console.log(e); });

I know javascript doesn’t look good, but if you want you can do everything chained:

listaNomeProjeto
    .filter(function(e) { return e.nomeProjeto === 'NomeProjeto2' })
    .map(function(e) { return e.subProjeto; })
    .forEach(function(e){ console.log(e); });

I find it much more readable than using loops :)

Browser other questions tagged

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