我有一个 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/