Skip to content
Advertisement

how do i copy an array correctly

im trying to make a copy of an array but when i change the copy it also changes the original. i have tried using Object.assign([], scenes), scenes.clone() and tried using a for loop

if(localStorage.getItem(saveName) == null){
    var nonLoopScenes = [...scenes];
    nonLoopScenes.forEach(element=>{
        element.objects.forEach(element2=>{
            element2.scene = null;
        });
    });
    console.log(nonLoopScenes);
    console.log(scenes);
    localStorage.setItem(saveName,JSON.stringify(scenes));
}

Advertisement

Answer

You can also try const arrayCopy = JSON.parse(JSON.stringify(initialArray)), although the method using the spread operator should work as well.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement