0

I am trying to copy an array to a new variable and then modify the array.

Code:

    var test = [
        { test: "test1", arr: ["1", "2", "3"] },
        { test: "test2", arr: ["4", "5", "6"] }
    ];

    console.log("test before", test);
    console.log("test before", test[1]);
    console.log("test before", test[1].arr);

    var t2 =  [...test] // used .slice(0) but same result
    t2[1].arr = t2[1].arr.slice(0, 1);

    console.log("test after", test[1].arr);
    console.log("t2", t2[1].arr);

output:

test before:  
0: {test: "test1", arr: Array(3)} //arr: (3) ["1", "2", "3"]
1: {test: "test2", arr: Array(1)} // arr: (1) ["4"]

test before: 
{test: "test2", arr: Array(3)} //arr: (1) "4"

test before: (3) ["4", "5", "6"]

test after: ["4"]

t2: ["4"]

As you can see spread operator/ slice() is modifying the original value.
I also tried to use var t2 = Object.Create(test) [same result].

1
  • @undefined Yeah, I want to modify t2[1].arr. It had 3 elements first, but I want only the first element in it so doing slice(). Commented Jan 31, 2019 at 16:58

2 Answers 2

1

When you assign a an Object/Array to a variable it doesnot copy it. I just sets a reference to original Object/Array. You should use Object.assign for shallow cloning and JSON.parse(JSON.stringify(obj)) for deep cloning
Note: arrays are actually objects in javascript

    var test = [
        { test: "test1", arr: ["1", "2", "3"] },
        { test: "test2", arr: ["4", "5", "6"] }
    ];
    
    console.log("test before", test);
    console.log("test before", test[1]);
    console.log("test before", test[1].arr);
    
    var t2 =  JSON.parse(JSON.stringify(test)) // used .slice(0) but same result
    t2[1].arr = t2[1].arr.slice(0, 1);
    
    console.log("test after", test[1].arr);
    console.log("t2", t2[1].arr);


However this JSON.parse(JOSN.stringify(obj)) is not much efficient and will give wrong output in some cases.

Using jQuery

$.extend(true, {}, obj);

Using lodash

_.cloneDeep(value)

here You can find detail about this

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

Comments

0

Array spread (or Array.slice()) are only shallow copy of original array, so sub object are still the same.

For more details about deep copy of objects, take a look at: How do you clone an Array of Objects in Javascript?

Comments

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.