0

Assume, following JSON Structure is existing:

[
  {
    "role_id": 1,
    "role_name": "Admin"
  },
  {
    "role_id": 2,
    "role_name": "Editor"
  }
]

and stored in $rootScope.roles.

What I need is:

$rootScope.roles[index -> where role_id == 2].rolename  // gets -> Editor

How can I do that in Angular?

  • Take a look at this: http://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript Does it help? – Rodmentou Nov 04 '15 at 19:47

3 Answers3

0

You will have to loop over the array and return the property of the object that matches the given 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;
        }
    }
};
taxicala
  • 21,408
  • 7
  • 37
  • 66
  • that is OK but not an elegant solution, there must be a better way than a iteration loop, isn't it? –  Nov 04 '15 at 20:18
  • As I know, underscore has a method, maybe I have to include it, into the project? –  Nov 04 '15 at 20:20
  • I suppose... anyway underscore will loop the array behind the scenes... If you don't have a map there is no way to do it without a loop. – taxicala Nov 04 '15 at 20:21
0

If you are looking for a more "single-line" solution, you can use JS array function find:

($rootScope.roles.find(function (x) { return x.role_id == 2; }) || {}).role_name;

When it is not found, find returns null so I substituted that possible result by {} so it does not throw an exception when accessing null.role_name. This way it will return undefined when the specified role_id is not found.

Note this method is a new technology and won't be available in every browser, more info in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Another "single-line" more stable solution would be to use filter:

($rootScope.roles.filter(function (x) { return x.role_id == 2; })[0] || {}).role_name;

This other method is more stable and can be found in every browser, more info in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Javier Conde
  • 2,553
  • 17
  • 25
0

ng-lodash is an elegant way:

role_name = lodash.pluck(lodash.where($rootScope.roles,{'role_id': 2 }),'role_name');