Get specific object by id from array of objects in AngularJS

前端 未结 17 1257
囚心锁ツ
囚心锁ツ 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 07:58

    I know I am too late to answer but it's always better to show up rather than not showing up at all :). ES6 way to get it:

    $http.get("data/SampleData.json").then(response => {
    let id = 'xyz';
    let item = response.data.results.find(result => result.id === id);
    console.log(item); //your desired item
    });
    
    0 讨论(0)
  • 2020-12-07 08:00
    $scope.olkes = [{'id':11, 'name':'---Zəhmət olmasa seçim edin---'},
                    {'id':15, 'name':'Türkyə'},
                    {'id':45, 'name':'Azərbaycan'},
                    {'id':60, 'name':'Rusya'},
                    {'id':64, 'name':'Gürcüstan'},
                    {'id':65, 'name':'Qazaxıstan'}];
    
    <span>{{(olkes | filter: {id:45})[0].name}}</span>
    

    output: Azərbaycan

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-07 08:04

    Unfortunately (unless I'm mistaken), I think you need to iterate over the results object.

    for(var i = 0; i < results.length; i += 1){
        var result = results[i];
        if(result.id === id){
            return result;
        }
    }
    

    At least this way it will break out of the iteration as soon as it finds the correct matching id.

    0 讨论(0)
  • 2020-12-07 08:06

    You can just loop over your array:

    var doc = { /* your json */ };
    
    function getById(arr, id) {
        for (var d = 0, len = arr.length; d < len; d += 1) {
            if (arr[d].id === id) {
                return arr[d];
            }
        }
    }
    
    var doc_id_2 = getById(doc.results, 2);
    

    If you don't want to write this messy loops, you can consider using underscore.js or Lo-Dash (example in the latter):

    var doc_id_2 = _.filter(doc.results, {id: 2})[0]
    
    0 讨论(0)
  • 2020-12-07 08:07

    If you can, design your JSON data structure by making use of the array indexes as IDs. You can even "normalize" your JSON arrays as long as you've no problem making use of the array indexes as "primary key" and "foreign key", something like RDBMS. As such, in future, you can even do something like this:

    function getParentById(childID) {
    var parentObject = parentArray[childArray[childID].parentID];
    return parentObject;
    }
    

    This is the solution "By Design". For your case, simply:

    var nameToFind = results[idToQuery - 1].name;
    

    Of course, if your ID format is something like "XX-0001" of which its array index is 0, then you can either do some string manipulation to map the ID; or else nothing can be done about that except through the iteration approach.

    0 讨论(0)
提交回复
热议问题