Get specific object by id from array of objects in AngularJS

前端 未结 17 1462
囚心锁ツ
囚心锁ツ 2020-12-07 07:20

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 wi

17条回答
  •  广开言路
    2020-12-07 08:12

    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

提交回复
热议问题