在Angular中查询JSON结构:找到正确的索引并获得它的特定属性
假设存在以下JSON结构:在Angular中查询JSON结构:找到正确的索引并获得它的特定属性,json,angularjs,querying,angularjs-rootscope,Json,Angularjs,Querying,Angularjs Rootscope,假设存在以下JSON结构: [ { "role_id": 1, "role_name": "Admin" }, { "role_id": 2, "role_name": "Editor" } ] 并存储在$rootScope.roles中 我需要的是: $rootScope.roles[index -> where role_id == 2].rolename // gets -> Editor 如何在Angular中执行此操作?
[
{
"role_id": 1,
"role_name": "Admin"
},
{
"role_id": 2,
"role_name": "Editor"
}
]
并存储在$rootScope.roles中
我需要的是:
$rootScope.roles[index -> where role_id == 2].rolename // gets -> Editor
如何在Angular中执行此操作?您必须循环数组并返回与给定id匹配的对象的属性:
function getRoleName(roleId) {
for (var i = 0; i < $rootScope.roles.length; i++) {
if ($rootScope.roles[i].role_id == roleId) {
return $rootScope.roles[i].role_name;
}
}
};
函数getRoleName(roleId){
对于(变量i=0;i<$rootScope.roles.length;i++){
if($rootScope.roles[i].role_id==roleId){
返回$rootScope.roles[i]。role\u name;
}
}
};
如果您正在寻找更“单线”的解决方案,您可以使用JS数组函数查找
:
($rootScope.roles.find(函数(x){return x.role_id==2;})|{})代码>
当未找到它时,find
返回null
,因此我用{}
替换了可能的结果,这样它在访问null.role\u name
时不会引发异常。这样,当找不到指定的角色id
时,它将返回未定义的
注意:此方法是一项新技术,不会在每个浏览器中都可用,更多信息请参见
另一种“单线”更稳定的解决方案是使用过滤器:
($rootScope.roles.filter(函数(x){return x.role_id==2;})[0]| |{})代码>
另一种方法更稳定,可以在每个浏览器中找到,在ng lodash中的更多信息是一种优雅的方式:
role_name = lodash.pluck(lodash.where($rootScope.roles,{'role_id': 2 }),'role_name');
看看这个:它有帮助吗?这很好,但不是一个优雅的解决方案,肯定有比迭代循环更好的方法,不是吗?正如我所知,下划线有一个方法,也许我必须将它包括在项目中?我想。。。无论如何,下划线将在幕后循环数组。。。如果你没有地图,没有循环就没有办法做到。