niko craft
niko craft

Reputation: 2977

How do I loop through 2d array if I do not know the indexes

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.

Upvotes: 0

Views: 62

Answers (2)

gyre
gyre

Reputation: 16777

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?"

Upvotes: 3

JohanP
JohanP

Reputation: 5472

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

Upvotes: 0

Related Questions