How to print a JSON array?

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: - In%% is received the value of a select box.

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

        }
    }

I search in $(this).val() , if I find the name I have to print all content inside nomeProjeto . Should I loop through the array that is within subProjeto ? Could you help me?

    
asked by anonymous 29.07.2015 / 17:55

1 answer

2

I'll suggest a different solution without using loops. First filter for what you're looking for with the filter method:

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 map method:

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

To display the list of subprojects, forEach :

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

I know that in javascript does not look pretty, 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:)

    
29.07.2015 / 18:15