0

My array looks like this:

var permissions = new Array();

permissions['role-1'] = new Array();
permissions['role-1']['permission-1'] = "perm1";
permissions['role-1']['permission-3'] = "perm3";
permissions['role-1']['permission-5'] = "perm5";
permissions['role-2']['permission-1'] = "perm1";
permissions['role-2']['permission-5'] = "perm5";

How would I loop through such an array and go through all the elements? I can't use for-loop since that would use integer indexes.

gyre
  • 16,369
  • 3
  • 37
  • 47
niko craft
  • 2,893
  • 5
  • 38
  • 67
  • 4
    You're using arrays like objects. That isn't *wrong* in JavaScript, but it's generally not done. You should use objects, and `Object.keys()` will give you a real array containing the property names. You can use that for iteration. – Pointy Mar 15 '17 at 22:54
  • 1
    Use an object and then use `for (var key in permissions)` to loop over the keys. – Barmar Mar 15 '17 at 22:57
  • Possible duplicate of [How do I loop through or enumerate a JavaScript object?](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – gyre Mar 15 '17 at 23:05

2 Answers2

3

You are confusing arrays (which are best suited to integer-indexed properties) with objects (which are designed to use any valid string as a property name). Objects are sometimes called "associative arrays," which makes the distinction a bit confusing.

Instead of using new Array(), you should use the object literal shorthand to initialize your permissions variable. Then, you can use Object.keys to get a list of the keys you used to create your object and do something with your key-value pairs:

var permissions = {
  'role-1': {
    'permission-1': 'perm1',
    'permission-3': 'perm3',
    'permission-4': 'perm1',
    'permission-5': 'perm5',
  },
  'role-2': {
    'permission-1': 'perm1',
    'permission-5': 'perm5'
  }
}

var object = permissions['role-1']

Object.keys(object).forEach(function (key) {
  // Do something with your key-value pairs
  console.log(key, this[key])
}, object)

For more information, see "How do I loop through or enumerate a JavaScript object?"

gyre
  • 16,369
  • 3
  • 37
  • 47
0

I would use an object to store that.

var permissions = {};
permissions['role-1'] = permissions['role-1'] || {};
permissions['role-1']['permission-1'] = "perm1";
permissions['role-1']['permission-3'] = "perm3";

Then you can iterate over the keys

for(var key in permissions)
   console.log(permissions[key]);
JohanP
  • 5,252
  • 2
  • 24
  • 34