Get specific object by id from array of objects in AngularJS

302,352

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

I just want to add something to Willemoes answer. The same code written directly inside the HTML will look like this:

{{(FooController.results | filter : {id: 1})[0].name }}

Assuming that "results" is a variable of your FooController and you want to display the "name" property of the filtered item.

Share:
302,352

Related videos on Youtube

mooonli
Author by

mooonli

Software Engineer & Sports Fanatic, interested in Java, JSF, Primefaces, Mobile, iOS, Photoshop & OSX.

Updated on January 04, 2020

Comments

  • mooonli
    mooonli over 4 years

    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

    • simonlchilds
      simonlchilds over 10 years
      Have you given it a go yourself? If so, can we see what you came up with?
    • mooonli
      mooonli over 10 years
      Well I have no idea which way would be the best using AngularJS. What I dont like is to iterate over the array and do a equals on the id. Maybe there is a better way?
    • Vijay Pande
      Vijay Pande over 10 years
      You should rely on underscorejs or similar libraries for such processing. AngularJS is MVVM framework and may not have api for this.
    • Adam
      Adam over 10 years
      @marcbaur - you have to iterate the array. Even if you use underscore, or something similar, it's functions, behind the scenes, are just iterating.
    • Ankush Kondhalkar
      Ankush Kondhalkar almost 9 years
      please add angular code for this
    • kiev
      kiev over 8 years
      looks like it's time to change the chosen answer.
  • simonlchilds
    simonlchilds over 10 years
    Why? Do you have anything to back that up?
  • simonlchilds
    simonlchilds over 10 years
    Well, do you know what..? I just went off to re-read Javascript - the good parts to counter your argument and I am wrong! For all this time I've been doing it wrong! It hasn't caused me any problems though... yet. I've updated my answer.
  • Ben Lesh
    Ben Lesh over 10 years
    ... I really hope after reading this answer people don't think it's a good idea to sort an array then do a binary search. Binary search is clever, sure, but only if the array is already sorted, and in reality is: 1. easy to poorly implement, 2. Harder to read if poorly implemented.
  • flup
    flup almost 10 years
    Actually, I'd think it does! After fetching the array, you can use the $filter function to filter out the item with the correct id.
  • Zoran P.
    Zoran P. almost 10 years
    This should be the accepted answer. I had the same question in my head and this answer is the only one that uses existing AngularJS and isn' reinventing the wheel. And yes, it is working.
  • genuinefafa
    genuinefafa almost 10 years
    I really love underscore, but, does it worse having another JavaScript library?
  • gregoltsov
    gregoltsov over 9 years
    Note that find can potentially return multiple objects. Since we only want one, we can use findWhere which only returns the first occurrence (which we know is the only occurrence), e.g. a = _.findWhere(results, {id: 2}).
  • Meki
    Meki over 9 years
    +1 for this being the accepted answer. Best solution using angular libraries.
  • Antonio E.
    Antonio E. over 9 years
    I would highly appreciate if the downvoters could motivate their decision.
  • Aaron Roller
    Aaron Roller almost 9 years
    A related topic I found useful for running the filter in an expression: stackoverflow.com/questions/17793751/…
  • Aaron Roller
    Aaron Roller almost 9 years
    Plunker with filter in an expression: plnkr.co/edit/yc0uZejGqWTcUVKvI7Tq?p=preview
  • Ryan.lay
    Ryan.lay almost 9 years
    Be aware that filters find by case insensitive substrings by default. So (foo.results, {id: 2}) returns [{id: 12}, {id: 2}], {id:222}] but (foo.results, function (d) {return d.id === 2;}) returns [{id: 2}]
  • Tillman32
    Tillman32 almost 9 years
    Should just do something like this: var object_by_id = $filter('filter')(foo.results, {id: 2 })[0]; - See my answer below.
  • The DIMM Reaper
    The DIMM Reaper over 8 years
    If your array has more than a trivial number of items, this will create a lot of unnecessary scopes which may slow down your application.
  • niklas
    niklas over 8 years
    how performant is angular filter compared to underscore solutions
  • Abhijeet
    Abhijeet about 8 years
    @Ena-How to check result of filter is not null or undefined ?
  • Ena
    Ena about 8 years
    I used this HTML variant because I was sure a result existed. I tried and if there is no result the console does not give any error, it simply leaves the text blank. If you need to do some logic if no result is found then I think the best way to go is Willemoes answer (js code inside controller). In that example, you should then check in HTML if single_object variable is null or undefined.
  • George Sharvadze
    George Sharvadze about 8 years
    {{(FooController.results | filter : {id: 1})[0].name }: true} - if somebody's looking for an exact match
  • Lekz Flores
    Lekz Flores almost 8 years
    What about filtering with two ids? I mean the second id comes from a nested data of the json.
  • mpgn
    mpgn over 7 years
    also catch id: 24 12 222 2002 etc
  • dukevin
    dukevin about 7 years
    what is the runtime of this?
  • abosancic
    abosancic almost 7 years
    By default javascript Array type has method find(). The find() method returns the value of the first element in the array that satisfies the provided testing function.
  • Roddy of the Frozen Peas
    Roddy of the Frozen Peas over 6 years
    I would think that the [0] would cause it to return the first result it finds from the collection, so it would only work if your collection is sorted and the object you're looking for is the first it finds during its iteration. Eg. if there's a id:12 that comes before id: 2, it would return id: 12.