1

I need to use a variable globally declared, but modify it for the use of a function:

var example = {
    selected: '0',
    list: {
        1: {
            value: '1',
            name: "example 1"
        },
        2: {
            value: '2',
            name: "example 2"
        },
        3: {
            value: '3',
            name: "example 3"
        }
    }
};

window.load(function () {
    var example2 = example;
    example2.info = "newinfo";
    // Use example 2
})

The problem is, after that, if I console.log(example), it contains the "info" variable, absolutely unwanted. I don't even see why it would have it, I purposely defined a new variable to avoid this.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeremy Belolo
  • 4,319
  • 6
  • 44
  • 88

1 Answers1

4

The single assignment keeps the reference to the original object. So any changes are reflected to the original object.

Just use JSON.stringify and JSON.parse for a copy.

var example2 = JSON.parse(JSON.stringify(example));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392