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
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
Using ES6 solution
For those still reading this answer, if you are using ES6 the find
method was added in arrays. So assuming the same collection, the solution'd be:
const foo = { "results": [ { "id": 12, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] }; foo.results.find(item => item.id === 2)
I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.
Angular solution (old solution)
I aimed to solve this problem by doing the following:
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) { var foo = { "results": [ { "id": 12, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] }; // We filter the array by id, the result is an array // so we select the element 0 single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0]; // If you want to see the result, just check the log console.log(single_object); }]);
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
For anyone looking at this old post, this is the easiest way to do it currently. It only requires an AngularJS $filter
. Its like Willemoes answer, but shorter and easier to understand.
{ "results": [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] } var object_by_id = $filter('filter')(foo.results, {id: 2 })[0]; // Returns { id: 2, name: "Beispiel" }
WARNING
As @mpgn says, this doesn't work properly. This will catch more results. Example: when you search 3 this will catch 23 too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With