json 从 AngularJS 中的对象数组中通过 id 获取特定对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19590063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:58:16  来源:igfitidea点击:

Get specific object by id from array of objects in AngularJS

javascriptarraysangularjsjsonobject

提问by mooonli

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.

我有一个 JSON 文件,其中包含我想在我的 AngularJS 网站上访问的一些数据。现在我想要的是从数组中只获取一个对象。所以我想要例如 ID 为 1 的 Item。

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:

我想使用 AngularJS $http 功能加载数据,如下所示:

$http.get("data/SampleData.json");

$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?

这是工作。但是我现在如何从我得到的数组中获取一个特定的数据对象(通过 id)$http.get

Thanks in advance for your help.

在此先感谢您的帮助。

Greets Marc

问候马克

采纳答案by Antonio E.

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

唯一的方法是遍历数组。显然,如果您确定结果按 id 排序,则可以进行二分查找

回答by Willemoes

Using ES6 solution

使用 ES6 解决方案

For those still reading this answer, if you are using ES6 the findmethod was added in arrays. So assuming the same collection, the solution'd be:

对于仍在阅读此答案的人,如果您使用的是 ES6,则该find方法已添加到数组中。所以假设相同的集合,解决方案是:

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 或任何其他框架的联系较少。纯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

Plunker:http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview

回答by Tillman32

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.

对于任何查看这篇旧帖子的人来说,这是目前最简单的方法。它只需要一个 AngularJS $filter。它就像 Willemoes 的答案,但更短且更容易理解。

{ 
    "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

警告

正如@mpgn 所说,这不能正常工作。这将捕获更多结果。示例:当您搜索 3 时,这也会捕获 23

回答by Jason Boerner

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

那么“a”将是您想要的数组的行,其中 id 等于 2

回答by Ena

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

我只想在Willemoes answer 中添加一些内容。直接在 HTML 中编写的相同代码将如下所示:

{{(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.

假设“results”是您的 FooController 的一个变量,并且您想要显示过滤项的“name”属性。

回答by James Kuta Simiyu

You can use ng-repeatand pick data only if data matches what you are looking for using ng-showfor example:

ng-repeat仅当数据与您要查找的内容相匹配时,您才能使用和选择数据ng-show,例如:

 <div ng-repeat="data in res.results" ng-show="data.id==1">
     {{data.name}}
 </div>    

回答by kamituel

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.jsor Lo-Dash(example in the latter):

如果你不想写这种乱七八糟的循环,你可以考虑使用underscore.jsLo-Dash(后者的例子):

var doc_id_2 = _.filter(doc.results, {id: 2})[0]

回答by Ali Adravi

If you want the list of items like city on the basis of state id then use

如果您想要基于状态 ID 的城市等项目列表,请使用

var state_Id = 5;
var items = ($filter('filter')(citylist, {stateId: state_Id }));

回答by simonlchilds

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.

至少这样它会在找到正确的匹配 id 后立即退出迭代。

回答by Musa

Why complicate the situation? this is simple write some function like this:

为什么要把情况复杂化?这很简单,写一些像这样的函数:

function findBySpecField(data, reqField, value, resField) {
    var container = data;
    for (var i = 0; i < container.length; i++) {
        if (container[i][reqField] == value) {
            return(container[i][resField]);
        }
    }
    return '';
}

Use Case:

用例:

var data=[{
            "id": 502100,
            "name": "B?rd? filial?"
        },
        {
            "id": 502122
            "name": "10 sayl? filial?"
        },
        {
            "id": 503176
            "name": "5 sayli filial?"
        }]

console.log('Result is  '+findBySpecField(data,'id','502100','name'));

output:

输出:

Result is B?rd? filial?

回答by Celal Muhtar

$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

输出:Az?rbaycan