I have an arreglo
object with nested arrays:
categorias =
[
{
0: 'agosto', 'Manuel': [
{
id: 12,
categoria: 'sociedad',
},
{
id: 13,
categoria: 'sociedad',
},
],
},
{
1: 'septiembre', 'Carlos': [
{
id: 14,
categoria: 'deportes',
}
],
},
]
I need to display the following:
agosto, Manuel
12 - sociedad
13 - sociedad
septiembre, Carlos
14 - deportes
I need to display the two keys I have on each object. I was trying to access the data, but I can't.
<div *ngFor ="let item of categorias | keyvalue" >
{{item.key}} {{item.value}}
<p *ngFor="let value of categorias[item.key]">
{{ value }}
</p>
</div>
I only get this output:
0 [object Object]
1 [object Object]
How can I do to display the data I need and also if a button is pressed get the value of each key, for example if I need to send agosto
y septiembre
or Manuel
y Carlos
as a parameter in a function:
funcion(key1, key2) {
console.log(Key1, Key2)
}
That in case of selecting the first object the values would be:
agosto, Manuel
I hope you can help me, thanks in advance.
It is recommended to format your array, in a more manageable way and avoid complex logic in HTML, if you use that data format in several places, it would be good to use a
pipe
, otherwise it would only be enough to create an internal method to carry out the formatting.In your case, you have an array of objects. And these objects have keys that you will use as data as well, so you will not only need to iterate through the elements, but also through the keys using
Object.keys()
.Here is a complete example:
I think the code speaks for itself, but I'll explain it anyway. Here I needed to access the index of each iteration of the
keys
, since I wasn't sure if this format will always be like this, and if it is, it will always hold that:But you have to be careful, here you have to understand that the keys of an object are ordered , that's why you can do that.
Once the array of objects is formatted, access would be more intuitive:
Here is a stackblitz with this implementation.