Reputation: 9662
In my app, I make an http request which returns a JSON.
Here is the structure of JSON: https://demo6902979.mockable.io/data
{
"6288ba45-3b41-4862-9fed-7271245b9c29": {
"id": "6288ba45-3b41-4862-9fed-7271245b9c29",
"name": "name1",
"possibilities": {
"a48382bf-dde6-479d-8456-beee63f592be": {
"id": "a48382bf-dde6-479d-8456-beee63f592be",
"data": "anydata1",
"style": null
},
"d62fb2d2-58a6-458c-9e7f-78774af4d9fe": {
"id": "d62fb2d2-58a6-458c-9e7f-78774af4d9fe",
"data": "anydata2",
"style": null
}
}
},
"860aefe6-ff70-436b-8d2b-554251e8fb59": {
"id": "860aefe6-ff70-436b-8d2b-554251e8fb59",
"name": "name2",
"possibilities": {
"e30ef32b-20c2-4ddc-8d5f-e5f1fc35a6b7": {
"id": "e30ef32b-20c2-4ddc-8d5f-e5f1fc35a6b7",
"data": "anydata3",
"style": null
},
"49e8b455-848c-4cb2-bb84-5b7b3bc5fc4a": {
"id": "49e8b455-848c-4cb2-bb84-5b7b3bc5fc4a",
"data": "anydata4",
"style": null
}
}
}
}
Here is my code:
return this.http.get(`https://demo6902979.mockable.io/data`)
.map((res: Response) => res.json())
.filter((choices) => choices.id === "6288ba45-3b41-4862-9fed-7271245b9c29")
.subscribe(
data => {
this.Data = data;
console.log('Data:', data);
},
error => {
console.log('Get data failed Error:', error);
}
);
I'm trying to make a filter
on this JSON to only get current id of "6288ba45-3b41-4862-9fed-7271245b9c29" for example. It doesn't work and returns nothing.
As i'm unable to filter, I delete the filter line for the moment and try to iterate through this JSON to get data and style. To access it, for example, using this.Data.possibilities.data
(i don't know how to retrieve possibilities ID to do a this.Data.possibilities.[UUID].data
or this.data.possibilities[0].data
).
I'm struggling to do that within my code. Console returns an Object formatted JSON and I don't really know how to iterate through it. I tried to use this.Data.forEach()
but it returns an error as forEach doesn't exist on the this.Data element.
Every solution I saw on Angular2 where all in ngFor, but I need to do this directly in component class.
Thanks for your help.
Upvotes: 3
Views: 3905
Reputation: 9284
filter works on Array. Your data (object literal) is not an array.
You can map the properties of of the object using Object.keys and then map them to the actual values.
var data = ...
Object.keys(a)
.map(key => data[key]})
.filter(choices => choices.id === "6288ba45-3b41-4862-9fed-7271245b9c29")
.subscribe(data => {
this.Data = data;
console.log('Data:', data);
},
error => {
console.log('Get data failed Error:', error);
});
Upvotes: 4