Get specific object by id from array of objects in AngularJS

前端 未结 17 1406
囚心锁ツ
囚心锁ツ 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:02

    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

提交回复
热议问题