Reputation: 5986
I want to store an array of information, with a subset of information for each one. so I want something like:
var users = [{userID:1, userName:robert}, {userID:2, userName:daniel}]
then to retrieve the variable:
users.userID // 1, 2
users.userName // robert, daniel
or something, i want to be able to get the information associated with the userID.
Upvotes: 0
Views: 103
Reputation: 9477
Here is one way to do it
var array1 = new Array(1,2,3,4);
var array2 = new Array(8,9,10,11,12,13);
var array3 = new Array( array1, array2);
console.log(array1);
console.log(array2);
console.log(array3);
Will give you the right results
Upvotes: 0
Reputation: 4104
Depending on your problem I would think about redoing the array along the line of the following
var users = { 'id1' : { 'userName' :'robert'},
'id2': { 'userName ': 'daniel'}};
alert(users.id1.userName);
alert( eval('users.id' + 1 + '.userName'));
Upvotes: 1
Reputation: 1637
Yes, you can do that, in a variety of ways. Suppose you have:
var users = [{userID: 1, userName: robert}, {userID: 2, userName: daniel}];
To retrieve the userID
and userName
for Robert, you have access them via users[0].userID
and users[0].userName
.
If instead you want to retrieve them by users.userID[0]
and users.userName[0]
, then you need to store it this way:
var users = {userID: [1, 2], userName: [robert, daniel]};
If you are asking how to transform the first form to the second, use this:
function transform(source) {
var result = {};
for (var i = 0; i < source.length; i++) {
for (property in source[i]) {
if (typeof result[property] == "undefined")
result[property] = [];
result[property].push(source[i][property]);
}
}
}
And use it this way:
var transformed_users = transform(users);
Do note that this transform function is specific to your data structure.
Upvotes: 0
Reputation: 29576
this generates an array of user IDs:
[{userID:1, userName:robert},
{userID:2, userName:daniel}].map(function (x) { return x.userID; });
Upvotes: 0
Reputation: 3491
This might help:
var desiredUserID = 2;
var userList = [ {userID: 1, userName: "robert"}, {userID:2, userName:"daniel"} ];
for(x=0;x<=userList.length;x++) {
if(userList[x].userID == desiredUserID){
alert(userList[x].userName);
}
}
Upvotes: 0