3

I have a game that I need to allow the user to restart. To do that, I need to save the state of an object by deep copying. From what I understand, the only way to deep copy with JavaScript is JSON.parse(JSON.stringify(object)).

I tried that with the below code, but when I call restartSection(), the output is an object that only contains the first level of nested arrays and objects, and all of those arrays and objects are empty. This dictionary/object I need to copy has 5-10 nested layers, so I need a way to properly deep copy it.

I tried Object.assign(backup_user_dict, user_dict) which worked as a shallow copy, but it contained all of the data including changes made since assigning the object which I know is because it's only storing a reference instead of the literal values.

Am I doing something wrong, or does stringify only work with the top layer of an object? I can't find any other solution. I've heard people use a module called lodash which I tried to use as well.

I put

<script type="module" src="lodash.js"></script>

in my HTML.

Then I put

import { cloneDeep } from lodash.js

at the top of my JavaScript file.

But I get "Cannot use import statement outside a module" as an error when I try to do that.

Could anyone help me figure out how to deep clone this object?

var user_dict = {}
var backup_user_dict = {}

function startGame() {
    function getEmail() {
        function submitEmail() {
            user_dict['email'] = email.value;
            console.log('email is ' + user_dict['email'])
            emailContainerElement.classList.add('hide')
            startButton.classList.add('hide')
            questionContainerElement.classList.remove('hide')
            backup_user_dict = JSON.parse(JSON.stringify(user_dict))
            nextQuestion()
        }
        emailContainerElement.classList.remove('hide')
        startButton.classList.add('hide')
        submitEmailButton.addEventListener('click', submitEmail)
    }
    getQuestions('conditions').then((snap) => {
        startButton.addEventListener('click', getEmail)
    })
}

function restartSection() {
    user_dict = JSON.parse(JSON.stringify(backup_user_dict))
   current_index = 0
   current_sub_index = 0 
   category = 'main_questions'
   console.log('restartSection backup_user_dict is ', backup_user_dict)
   console.log('restartSection user_dict is ', user_dict)
   nextQuestion()
}

0 Answers0