totoaussi
totoaussi

Reputation: 731

How to preserve nested array value when modify a value of an cloned array?

I have a default nested array called default_array, very simple :

default_array = [
        ["a", "b", "c"] 
];

And I create a obj called obj where the value of his array attribute is the copy of default_array :

obj = {

    "array" : default_array.slice(0)
};

But when I modify a element of the obj.array like this :

obj.array[0][0] = "z";

This modify also the default_array. I want this modification doesn't affect default_array. I want to preserve default_array.

Any idea ?

Upvotes: 0

Views: 53

Answers (4)

Oleksandr T.
Oleksandr T.

Reputation: 77482

function copy(array) {
    var result = [];
    for (var i = 0, len = array.length; i < len; i++) {
        result.push(array[i].slice());
    }
    return result;
}

var default_array = [
    ["a", "b", "c"]
];
var obj = {
    "array": copy(default_array)
};

obj.array[0][0] = 'z';
console.log(obj.array);
console.log(default_array);

Upvotes: 2

Abhas Tandon
Abhas Tandon

Reputation: 1889

Try using map or Or you can use combination of JSON.parse & JSON.stringify since you are having a nested/multidimensional array:

default_array = [
    ["a", "b", "c"]
];
var newArray = default_array.map(function(arr) {
    return arr.slice();
});
//Or you can use combination of JSON.parse & Stringify
var newArray = JSON.parse(JSON.stringify(default_array));
obj = {
    "array": newArray.slice(0)
};

Upvotes: 0

Andrei Kropotin
Andrei Kropotin

Reputation: 293

You can try this:

obj = {
    "array" : JSON.parse(JSON.stringify(default_array))
};

Upvotes: 0

Fabio Beltramini
Fabio Beltramini

Reputation: 2511

This may be overkill for your problem, but if you are running into it more and more, consider using Immutable.js

It provides efficient immutable datatypes.... just look at https://facebook.github.io/immutable-js/ for example code that uses the ibrary.

Upvotes: 0

Related Questions