How to group values from a json

Asked

Viewed 208 times

0

I have a JSON that looks like this:

[
    {
        "id": 459,
        "razao_social": "Testosvaldo de Testousa",
        "cidade": "Testolandia",
    },
    {
        "id": 472,
        "razao_social": "teste trr",
        "cidade": "Belo Horizonte",
    },
    {
        "id": 473,
        "razao_social": "teste trr",
        "cidade": "Belo Horizonte",
    }
]

How do I return a JSON grouped by city?

  • It can help you: https://stackoverflow.com/questions/6487167/deserializing-a-json-into-a-javascript-object

  • What result do you expect?

  • Would that be the last answer? https://stackoverflow.com/questions/22961446/group-by-for-json-data-using-jquery

1 answer

4


You can create a new object, browse through json using a for, and add a new node to each city, and go grouping the cities within that node, like this:

var jsData=[
    {
        "id": 459,
        "razao_social": "Testosvaldo de Testousa",
        "cidade": "Testolandia",
    },
    {
        "id": 472,
        "razao_social": "teste trr",
        "cidade": "Belo Horizonte",
    },
    {
        "id": 473,
        "razao_social": "teste trr",
        "cidade": "Belo Horizonte",
    }
];


var agrupadoPorCidade = {};
for (var key in jsData) {
    var cidade = jsData[key].cidade;  
    if (!agrupadoPorCidade[cidade]) {
        agrupadoPorCidade[cidade] = [];
    }
    agrupadoPorCidade[cidade].push(jsData[key]);
}

console.log(agrupadoPorCidade);

Browser other questions tagged

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