I have been having hard times trying to get to one specific key/value which is nested into JSON objects
This is the API response
response: {
estabelecimento: {
atividades_secundarias: [{
id: "6209100",
secao: "J",
divisao: "62",
grupo: "62.0",
classe: "62.09-1",
subclasse: "6209-1/00",
descricao: "Suporte",
contribuinte: false
},
{
id: "7020400",
secao: "M",
divisao: "70",
grupo: "70.2",
classe: "70.20-4",
subclasse: "7020-4/00",
descricao: "Atividades",
contribuinte: false
},
{
id: "8211300",
secao: "N",
divisao: "82",
grupo: "82.1",
classe: "82.11-3",
subclasse: "8211-3/00",
descricao: "Serviços",
contribuinte: false
}
]
}
}
The GOAL is to return all descricao items from atividades_secundarias object and store them as a string?
In this case: "Suporte / Atividades / Servicos" … something like this
Following are the things I have tried:
- Accessing
descricao
value by key string
$.each(response.estabelecimento.atividades_secundarias,function(index, item) {
$.each(index, function (key, val) {
console.log(val["descricao"]);
});
});
- Accessing
descricao
value usingthis
operator
$.each(response.estabelecimento.atividades_secundarias, function(index, item) {
$.each(index.id, function (key, val) {
console.log(this.descricao);
});
});
I believe it’s something very subtle I’m missing.
Thanks
2
Answers
If you want to create an array of "descricao" values, you can simply do this:
You don’t need a second $.each loop.
Use
$.map()
to iterate throughatividades_secundarias
.Figure I
On each iteration, use
Object.keys()
on each object (call each objectx
) within the array. You’ll get an array of each object’s keys.Figure II
Next find the key
descricao
in each object with.includes()
and return it’s valuex.descricao
ORnull
if the object doesn’t have that particular key.Figure III
$.map()
returns an array so if you want a string simply use.join()
.Figure IV