5
Suppose I have the following given JSON:
const dados = {"animais":[
{
"id":1,
"tipo":"Cachorro",
"nome":"Max",
"tags":"Border Collier"
},{
"id":2,
"tipo":"Cachorro",
"nome":"Fini",
"tags":"Lhasa Apso"
},{
"id":3,
"tipo":"Gato",
"nome":"Luna",
"tags":"Siames"
},{
"id":4,
"tipo":"Papagaio",
"nome":"Loro",
"tags":"Curica"
},{
"id":5,
"tipo":"Cachorro",
"nome":"Rock",
"tags":"Pitbull"
}
]
}
And I need to generate a list as follows:
const dados = {
"Cachorros":[
{
"id":1,
"nome":"Max",
"tags":"Border Collier"
},{
"id":2,
"nome":"Fini",
"tags":"Lhasa Apso"
},{
"id":5,
"nome":"Rock",
"tags":"Pitbull"
}],
"Gatos":[{
"id":3,
"nome":"Luna",
"tags":"Siames"
}],
"Papagaios":[{
"id":4,
"nome":"Loro",
"tags":"Curica"
}
]
}
What would be the fastest or easiest way to make such a transformation? I’m learning Javascript now and need to handle this data from an API to display it in a table. My logic is still weak, I searched filter, map and reduce methods but could not imagine a way to do it.
Then, could I calculate, for example, how many dogs are there in the new list? And cats and parrots. I imagine this part is the easiest using a length.
Thank you very much for the reply Andrade. But what if I have a JSON with a huge number of different animal types, there is a way to do without instantiating a Let dog, etc.? For example, using a while or for to traverse the Array.
– Lucas Morse
It was as I commented, depending on the data does not get performatic, I left only as an example even has to do without creating the variables, but, would be more complex. The @Sergio’s answer is perfect,pq, regardless of the amount of items in the arrays and is very lean, although it is more complex for those who are learning, if you have doubts about how much his answer can question it.
– LeAndrade