Reputation: 107
I need an array structure that includes the user id as array key and can store more information about that user (2 dimensional array). In my case if he is allowed to perform database requests, these are represented by request id and true/false.
Each user can have multiple requests
For example:
User id =14 and requests ids =22 and true and 45 and false
User id =12 and requests ids =44 and false and 77 and false
It should look like this:
var users_rights={14:{22:true,45:false},12:{44:false,77:false}}
I’m struggling with js syntax since
var id[14] ;
Creates an array with 14 elements and the rest of the array is empty but I want an array where at the 14 position all my requests information are stored.
Upvotes: 0
Views: 696
Reputation: 2613
You can use the [] syntax with regular JS objects like the one you describe. Simple example:
var ob = {10: {11:true}, 12: {13: false}};
console.log(ob[10]); //Displays the object {11:true}
console.log(ob[10][11]); //Displays true
Upvotes: 1
Reputation: 1075189
It sounds as though you don't want an array at all, you want an object with object values for its properties (or if you're using ES2015, a Map
of Map
s).
Your
var users_rights={14:{22:true,45:false},12:{44:false,77:false}}
(which is perfectly valid syntax, other than you should have a ;
at the end) gives you the former: You index into it with the user ID (14
) and then index into the object you get as a result with the request IDs (22
and/or 45
), which gives you a boolean value.
You create an object like this:
var users_rights = {};
You add a property to it for the key 14
like this:
users_rights[14] = {};
You add properties to that the same way:
users_rights[14][22] = true;
users_rights[14][45] = false;
These objects are just plain objects, not arrays. Brackets notation works with them just fine (in fact, it's the fact that brackets notation works with objects that makes it work with arrays, because standard arrays in JavaScript aren't really arrays at all).
Upvotes: 0
Reputation: 81
If you create the array first, then assign the values you will edit only the nth element e.g.
var id = [];
id[14] = 'xyz'
Gives an array with 14 undefined's and 'xyz' as the 15th element.
Upvotes: 0