SC_Chupacabra
SC_Chupacabra

Reputation: 14357

For..In Loop Overwriting ALL Array Values

I'm trying to use a for..in loop to iterate through a list of names, add them to a template object ('group'), then add each complete object to an array ('queryList'). This isn't working because each iteration is overwriting ALL values in the array. Any suggestions why this is happening?

// BATTERY OBJECT
var groupList = [ "LOGIN", "BROWSE", "SEARCH"];

// GROUP OBJECT
var group = {dbName: 'CARS', name: '', collectionName: 'group'};

// INIT VARS
var groupName = '',
    queryList = [];

// COMPILATION FUNCTION
var buildGroupQueries = function(group){

    // BUILD BATCH OF QUERIES   
    for (var i in groupList){
        groupName = groupList[i];
        group.name = groupName;
        queryList[i] = group;
    }
    console.log(queryList);

}

buildGroupQueries(group);

It should look like:

[
    {"dbName":"CARS","name":"LOGIN","collectionName":"group"},
    {"dbName":"CARS","name":"BROWSE","collectionName":"group"},
    {"dbName":"CARS","name":"SEARCH","collectionName":"group"}
]

Instead I'm getting:

[
    {"dbName":"CARS","name":"SEARCH","collectionName":"group"},
    {"dbName":"CARS","name":"SEARCH","collectionName":"group"},
    {"dbName":"CARS","name":"SEARCH","collectionName":"group"}
]

Upvotes: 3

Views: 2685

Answers (2)

Luca Borrione
Luca Borrione

Reputation: 16992

You are creating an array of elements referring to the same object, so they all show the same name coinciding with the last time you changed it, which is "SEARCH" in your example.
You have to refer each element to a new object created from the one you want to use as a template.
To do so you can either loop over its properties or clone it as shown below:

// BATTERY OBJECT
var groupList = [ "LOGIN", "BROWSE", "SEARCH"];

// GROUP OBJECT
var group = {dbName: 'CARS', name: '', collectionName: 'group'};

// INIT VARS
var groupName = '',
    queryList = [];

// COMPILATION FUNCTION
var buildGroupQueries = function(group){
    var i, _group;

    // BUILD BATCH OF QUERIES
    for (i in groupList){
        _group        = JSON.parse(JSON.stringify(group));
        groupName     = groupList[i];
        _group.name   = groupName;
        queryList[i]  = _group;
    }
    console.log(queryList);

}

buildGroupQueries(group);

Upvotes: 2

Anarion
Anarion

Reputation: 1038

You modify the group object each time, but you need to modify its copy.

Add this code just after your line for (var i in groupList){

var _group = {};
for (var j in group){ _group[j] = group[j]; }

On each iteration you create a new object and copy to it all properties from the master object.

Upvotes: 2

Related Questions