0

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 ?

3
  • Try var copy = default_array.map(function(e) { return e; }); Then use copy Commented Oct 16, 2015 at 17:57
  • .map not supported by IE8. Commented Oct 16, 2015 at 18:03
  • Use Pollyfill from MDN. This should be added in Question, IE8 Commented Oct 16, 2015 at 18:09

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Extended version for case if in parent array not only arrays jsfiddle.net/_alexander_/o96hL8L9/1
0

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.

Comments

0

You can try this:

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

Comments

0

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)
};

3 Comments

map not supported by IE8. Without .map() and without jquery is possible ?
you can use combination of JSON.parse & JSON.stringify see edit
Nit: This will not work if all the elements of default_array are not arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.