Javascript 从和数组中获取特定对象而无需循环的最佳方法
在我的角度应用程序的一个控制器中,我有一个变量集,如下所示Javascript 从和数组中获取特定对象而无需循环的最佳方法,javascript,angularjs,Javascript,Angularjs,在我的角度应用程序的一个控制器中,我有一个变量集,如下所示 SomeService.get({}, function(data){ // this sets xyz as the list of the data retrieved // from the resource within the controllers scope $scope.xyz = data.objects; }); angular.forEach($scope.xyz, functi
SomeService.get({}, function(data){
// this sets xyz as the list of the data retrieved
// from the resource within the controllers scope
$scope.xyz = data.objects;
});
angular.forEach($scope.xyz, function(obj){ return obj.id == 1;});
现在,$scope.xyz
看起来像
[
0: {id: 1, ...more data here ...},
1: {id: 2, ...more data here ...},
2: {id: 3, ...more data here ...},
3: {id: 4, ...more data here ...},
4: {id: 5, ...more data here ...},
5: {id: 6, ...more data here ...},
]
我试图做的是使用id
属性(而不是列表索引)在xyz中获取一个对象。我知道我可以如下迭代数组
SomeService.get({}, function(data){
// this sets xyz as the list of the data retrieved
// from the resource within the controllers scope
$scope.xyz = data.objects;
});
angular.forEach($scope.xyz, function(obj){ return obj.id == 1;});
但是有没有一种方法可以不在列表上循环执行呢?不,除非满足一些先决条件,否则你不能真正避免循环(
O(n)
)
- 如果数组按id排序,则可以使用二进制搜索算法(
)O(logn)
- 如果数组索引始终对应于id-1(或类似的简单公式),则可以在
中直接访问它O(1)
如果最初没有满足这些条件,但您需要多次通过id访问这些项目,那么将它们以这种形式呈现(排序/构建哈希图)可能会有所帮助。尽管这一点在一年前就已经得到了回答,因为这是谷歌的顶级结果之一,我想我可以添加以下建议,这可能是最简单的过滤方法。 将$filter注入控制器后
var result = $filter('filter')($scope.xyz, {id:"1"});
参考:
检查建议的答案是使用jQuery功能。您是否尝试不使用下划线/lo破折号或类似的实用程序带?@Stewie嗯,我对选项持开放态度,但如果有一种方法可以不依赖库来处理如此小的用例,那将是一件好事。Angular不会尝试提供如此低级的实用程序,所以这个问题都是关于无循环映射的JavaScript解决方案。关于这件事,我想说@Bergi的答案是你能期待的最好的答案。是的,即使我这么认为。谢谢你,伙计。