Absolutely, there are several ways to achieve this. Let's say you have:
var users = [{userID: 1, userName: robert}, {userID: 2, userName: daniel}];
To get the userID
and userName
for Robert, you can access them using users[0].userID
and users[0].userName
.
If you prefer to access them using users.userID[0]
and users.userName[0]
, you should structure it like this:
var users = {userID: [1, 2], userName: [robert, daniel]};
If you're wondering how to convert the first format to the second one, you can use this function:
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]);
}
}
}
Apply it like so:
var transformed_users = transform(users);
Keep in mind that this transformation function is tailored to your specific data structure.