gpt4 book ai didi

javascript - 在不循环的情况下从数组中获取特定对象的最佳方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:19 26 4
gpt4 key购买 nike

在我的 Angular 应用程序的一个 Controller 中,我有一个变量集如下。

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;
});

现在 $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 中获取一个对象。我知道我可以按如下方式遍历数组。

angular.forEach($scope.xyz, function(obj){ return obj.id == 1;});

但是有没有一种方法可以在不遍历列表的情况下做到这一点?

最佳答案

虽然这已经在一年前得到回答,但由于这是 Google 中的顶级结果之一,我想我可以添加以下建议,这可能是最简单的过滤方法。将 $filter 注入(inject) Controller 后,

var result = $filter('filter')($scope.xyz, {id:"1"});

引用: https://docs.angularjs.org/api/ng/filter/filter

关于javascript - 在不循环的情况下从数组中获取特定对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15411337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com