mooonli mooonli - 21 days ago 27
AngularJS Question

Get specific JSON object by id from JSON array in AngularJS

I have a JSON file containing some data I d like to access on my AngularJS website. Now what I want is to get only one object from the array. So I d like for example Item with id 1.

The data looks like this:

{ "results": [
{
"id": 1,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] }


I d like to load the data with AngularJS $http functionality like this:

$http.get("data/SampleData.json");


which is working. But how can I now get a specific data object (by id) from the array I get from
$http.get
?

Thanks in advance for your help.

Greets
Marc

Answer

The only way to do this is to iterate over the array. Obviously if you are sure that the results are ordered by id you can do a binary search