Get specific object by id from array of objects in AngularJS

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

提交回复
热议问题