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

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

数据如下:

{ "results": [
    {
        "id": 1,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] }

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

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

这是有效的。但是我现在如何从从 $http.get 获得的数组中获取特定的数据对象(通过 id)?

提前感谢您的帮助。

问候 马克

最佳答案

使用 ES6 解决方案

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

const foo = { "results": [
    {
        "id": 12,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] };
foo.results.find(item => item.id === 2)

我现在完全赞成这个解决方案,因为它与 Angular 或任何其他框架的联系较少。纯 Javascript。

Angular 解决方案(旧解决方案)

我打算通过以下方式解决这个问题:

$filter('filter')(foo.results, {id: 1})[0];

一个用例示例:

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

https://stackoverflow.com/questions/19590063/

相关文章:

json - 如何在 Swift 中解码 HTML 实体?

sql-server - 在 SQL 中解析 JSON

json - 如何使用标准 Scala 类在 Scala 中解析 JSON?

c# - ASP.NET Core 返回带有状态码的 JSON

javascript - JSON.parse 意外字符错误

android - 将 ArrayList 转换为 JSONArray

json - curl json 通过终端向 Rails 应用程序发布请求

javascript - 如何使用 html 表单数据发送 JSON 对象

python - UnicodeDecodeError : 'utf8' codec can't d

javascript - 无法使用 "-"破折号访问 JSON 属性