Group elements of a JSON

0

I have the following JSON, which each record has a city, but the same city can be in many records at once.

{
  "data": [
    {
      "numero": "123",
      "nombre": "jorge",
      "ciudad": "Tokio"
    },
    {
      "numero": "222",
      "nombre": "juan",
      "ciudad": "Tokio"
    },
    {
      "numero": "777",
      "nombre": "daniel",
      "ciudad": "Tokio"
    },
    {
      "numero": "333",
      "nombre": "pedro",
      "ciudad": "New york"
    },
    {
      "numero": "444",
      "nombre": "luis",
      "ciudad": "New york"
    },
    {
      "numero": "555",
      "nombre": "andres",
      "ciudad": "Buenos Aires"
    }
  ]
}

I need to be able to group by city and only show 1 of them independent of the times it is repeated besides bring the number of elements found example:

  

result: (Tokyo, New york, Buenos Aires, 3)

     

/ * "3" is the number of cities found * /

Thank you very much for your attention, I will be attentive to your replies greetings.

    
asked by Javier Antonio Aguayo Aguilar 09.08.2018 в 18:13
source

2 answers

1

You can do it with a Map, since the key will never be repeated, and as a value you can use an array of objects.

const data = {
"data": [
{
  "numero": "123",
  "nombre": "jorge",
  "ciudad": "Tokio"
},
{
  "numero": "222",
  "nombre": "juan",
  "ciudad": "Tokio"
},
{
  "numero": "777",
  "nombre": "daniel",
  "ciudad": "Tokio"
},
{
  "numero": "333",
  "nombre": "pedro",
  "ciudad": "New york"
},
{
  "numero": "444",
  "nombre": "luis",
  "ciudad": "New york"
},
{
  "numero": "555",
  "nombre": "andres",
  "ciudad": "Buenos Aires"
}
]
}

const map = data.data.reduce((map, item) => map.set(item.ciudad, item), new Map());

console.log(map.get('Buenos Aires').length);//1
    
answered by 10.08.2018 в 13:57
0

You can do it by iterating through your data and generating a new array of unique cities. Something like this:

var data = {
  "data": [
    {
      "numero": "123",
      "nombre": "jorge",
      "ciudad": "Tokio"
    },
    {
      "numero": "222",
      "nombre": "juan",
      "ciudad": "Tokio"
    },
    {
      "numero": "777",
      "nombre": "daniel",
      "ciudad": "Tokio"
    },
    {
      "numero": "333",
      "nombre": "pedro",
      "ciudad": "New york"
    },
    {
      "numero": "444",
      "nombre": "luis",
      "ciudad": "New york"
    },
    {
      "numero": "555",
      "nombre": "andres",
      "ciudad": "Buenos Aires"
    }
  ]
};

var ciudades = [];

data.data.forEach(function(dato) {
  if (ciudades.indexOf(dato.ciudad) == -1) {
    ciudades.push(dato.ciudad);
  }
});
console.log(ciudades);
console.log(ciudades.length);
    
answered by 09.08.2018 в 18:18