Push is overwriting previous data in array

I'm passing a string which looks something like: "John.Doe.100.Newbie-David.Miller.250.Veteran-" to the SplitDatabase function which splits the string appropriately and assigns the values to the UserDataEntry object. The UserDataEntry object is then pushed in to the global UserData array which is supposed to store all the user data.

For some reason though, the UserData.push(UserDataEntry) part seems to be overwriting previous data in the UserData array. The alert in the 1st loop shows the correct data as it loops, but alert in the second loop at the bottom just shows the last record over and over again.

I'm not sure why this is?

var UserData = [];


function SplitDatabase(result) {
    var RawUsers = result.split('-');
    var UserDataEntry = {};


    for (var i = 0; i < (RawUsers.length - 1); i++) {
        var tempUserData = RawUsers[i].split('.');
        for (var x = 0; x < (tempUserData.length); x++) {

            switch (x) {
            case 0:
                UserDataEntry.firstname = tempUserData[x];
                break;
            case 1:
                UserDataEntry.lastname = tempUserData[x];
                break;
            case 2:
                UserDataEntry.points = tempUserData[x];
                break;
            case 3:
                UserDataEntry.rank = tempUserData[x];
                UserData.push(UserDataEntry);
                alert(UserData[i].firstname);
                break;
            }
        }

    }

    for (var i = 0; i < (UserData.length); i++) {  
        alert(UserData[i].firstname);
    }

}

Answers:

Answer

Calling push will not copy your object, because JavaScript Objects are passed by reference: you're pushing the same Object as every array entry.

You can fix this easily by moving the var UserDataEntry = {}; inside the loop body, so that a new object is created each loop iteration:

    for (var x = 0; x < (tempUserData.length); x++) {
         var UserDataEntry = {};
Answer

Put your line var UserDataEntry = {} inside the for loop.

Right now, you only have one object, and you're setting each part of the array to that object. You overwrite the members in your loop.

If you create a new object inside the loop, you'll add all new members in to the array.

Answer

var UserDataEntry = {}; - {} is very important.

var UserDataEntry; -- If we put this in loop still have a same problem.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.