Skip to content
Advertisement

JavaScript – Store multiple objects in array and access their properties via

So here I have a database of user objects and I would like to push each one into the ‘allUsers’ array. I then want to be able to loop through this array and access a property e.g. allUsers[i].genrePref. How do I push all of these variables into the array to store them like [user, jon, lucy, mike, luke...

    // Users
    var user = {username: user9110252username, genrePref: user9110252genre};
    var jon = {username: 'Jon', genrePref: 'rock'};
    var lucy = {username: 'Lucy', genrePref: 'pop'};
    var mike = {username: 'Mike', genrePref: 'rock'};
    var luke = {username: 'Luke', genrePref: 'house'};
    var james = {username: 'James', genrePref: 'house'};
    var dave = {username: 'Dave', genrePref: 'bass'};
    var sarah = {username: 'Sarah', genrePref: 'country'};
    var natalie = {username: 'Natalie', genrePref: 'bass'};


    // Users array
    var allUsers = [];

Advertisement

Answer

To just add the variables to the array, there’s really no other way except to do exactly what you did in your example, which is to manually add each variable to your array.

// Users array
var allUsers = [
    user,
    jon,
    lucy,
    mike,
    luke,
    james,
    dave,
    sarah,
    natalie
];

BUT, you could probably do something a little more robust, which in its simplest form is to define an object literal called users that contains each user object. Then you not only have the added benefit of a pseudo-namespacing around your users, you can easily iterate over the object literal and put each user into an array, as such:

// Users
var users = {
    user : {username: user9110252username, genrePref: user9110252genre},
    jon : {username: 'Jon', genrePref: 'rock'},
    lucy : {username: 'Lucy', genrePref: 'pop'},
    mike : {username: 'Mike', genrePref: 'rock'},
    luke : {username: 'Luke', genrePref: 'house'},
    james : {username: 'James', genrePref: 'house'},
    dave : {username: 'Dave', genrePref: 'bass'},
    sarah : {username: 'Sarah', genrePref: 'country'},
    natalie : {username: 'Natalie', genrePref: 'bass'}
}

// Users array
var allUsers = [];

// Populate users array
for(var key in users) {
    allUsers.push(users[key]);
}

One last note on style. You should probably avoid explicitly setting the ‘key’ of each user object in your users object literal to be the name of the user. If you have any users with the same name, this model will break. Instead, consider generating some kind of unique key, like a guid, or some other unique value for each user. That way you’ll never accidentally overwrite an entry in your users object if, for example, you are populating this users object from some database and two or more users happen to have the same name.

Good luck.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement