Get specific object by id from array of objects in AngularJS Get specific object by id from array of objects in AngularJS angularjs angularjs

Get specific object by id from array of objects in AngularJS


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


personally i use underscore for this kind of stuff... so

a = _.find(results,function(rw){ return rw.id == 2 });

then "a" would be the row that you wanted of your array where the id was equal to 2