Kyon147
Kyon147

Reputation: 798

Updating javascript Array inside object updates all arrays in the object

I think I am having a bit of a stupid moment here, so hoping you can help.

I have an object discount_arr which holds an associative array of numbers. When trying to update a specific array though, it seems to apply to all the arrays in the object.

Both of these update all the items which is not what I want.

discount_arr.EMAILVIP[0] = 100;

discount_arr[EMAILVIP][0] = 100;

enter image description here

I am sure I am missing something really obvious...

EDIT:

To populate the object I use this code: This loops through another set of data to only pull through unique codes which are used as the array item itself.

var default_days = []; is an array of defaults which I am looking to overwrite. I populate it with a number of 0 values based on days in the month.

  var unique = {};
    for( var i in data ){

        //console.log(data[i]);

        for (var j in data[i]){

            //console.log(j);

            if( typeof(unique[j]) === "undefined"){
                discount_arr[j] = default_days;
            }
            unique[j] = 0;

        }

    }

Upvotes: 1

Views: 256

Answers (1)

Vandesh
Vandesh

Reputation: 6894

The problem is that all of your arrays refer to the same default_days array.

Use discount_arr[j] = [...default_days]; instead to copy array

If you're not using ES6, then discount_arr[j] = default_days.concat(); should do it

Upvotes: 3

Related Questions