Using ES6 solution
(使用ES6解决方案)
For those still reading this answer, if you are using ES6 the find
method was added in arrays.
(对于仍在阅读此答案的人,如果您使用的是ES6,则会在数组中添加find
方法。)
So assuming the same collection, the solution'd be:(所以假设相同的集合,解决方案是:)
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.(纯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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…