Reinitialize the nested property of an object in JavaScript

I've encountered an issue while using the Vue3 composition API where attempting to reset a form with nested properties using Object.assign does not work as expected.

const initialForm = {
    name: "",
    details: {
        type: ""
    }
};

const form = reactive({ ...initialForm });

const resetForm = () => {
    Object.assign(form, initialForm);
}

Although the "name" property is successfully reset, the "details.type" property remains unchanged. Any suggestions on how to properly reset the entire form including nested properties?

Answer №1

When using the spread operator ... and Object.assign, keep in mind that they only perform a shallow copy.

This means that nested references are not changed. So, the value of details.type from the initialForm remains the same in form.details.type.

To effectively copy an object deeply when assigning to form or when resetting the form, you will need to use a method like _.cloneDeep.

const initialForm = {
    name: "",
    details: {
        type: ""
    }
};

let form = reactive(_.cloneDeep(initialForm));

const resetForm = () => {
    form = _.cloneDeep(initialForm);
}

If you prefer not to rely on external packages like lodash:

const initialForm = {
    name: "",
    details: {
        type: ""
    }
};

let form = {...initialForm, details: {...initialForm.details}};

const resetForm = () => {
    form = {...initialForm, details: {...initialForm.details}};
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue 3 required but not found as a peer dependency

Every time I execute npm list -g --depth=0 command in cmd, npm throws this error. +-- @vue/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086b6461483c263d263e">[email protected]</a> +-- <a href="/cdn-cgi/l/emai ...

Guide to ensuring every request in an Express.js application contains a cookie

Currently, I am in the process of developing a CRUD application using both React and Node. As part of my development, it is crucial for me to validate whether the cookie is present or not for each request. app.all("*", (req,res) => { // If the cookie ...

Lost variable during the ajax call

Encountering a peculiar issue while attempting to pass a variable as a parameter to a nested ajax request callback: $('form').on('submit',function(e){ $.ajaxSetup({ header:$('meta[name="_token"]').attr('conte ...

"Setting the minimum length for multiple auto-complete suggestions in

How can I dynamically set the minLength of an input field based on whether a numeric value is coming from the "#lookup" field? Is there a way to achieve this using JavaScript and jQuery? <script type="text/javascript"> $(document).ready(function() ...

JavaScript causing Axios network error

Recently, I've started exploring the combination of axios and stripe in my project but unfortunately, I have encountered some challenges. Whenever I attempt to initiate a post request using axios, an error pops up which looks like this: https://i.sta ...

Node.js function failing to return any value

I am facing an issue with retrieving the value of a function as it is not returning anything. Below is the function I am using (Request is an async function that sends a get request): var getVolumesOKCoin = function(pair){ request('https://www.okc ...

Executing a secondary function only once after a repeated condition has been met

Functionality: The secondary function is triggered when the initial condition is met and satisfied. This means that if the condition is true, the secondary function will be executed. However, the secondary function should only be triggered once until the ...

Exploring the differences between arrays and objects provided by users

I am working on a functionality that involves comparing user input with predefined usernames and passwords. Here is what I have so far: var sys = { users: [ {user: 'user1', pass: 'qwerty'}, {user: 'Ragnar&apos ...

Managing browser window close events in a Vue.js application

As the user prepares to close the browser, I aim to transmit information to the server indicating that they have gone offline. Despite extensive research into this matter over a period of days, I have yet to uncover a solution. Can anyone provide guidanc ...

My onClick AngularJS function contains a for loop that is not functioning properly upon initial click

When I click on a student's name in my AngularJS app, the program is supposed to show the student's full name and list of tuitions. However, I am encountering an issue where the for loop does not work on the first click, but it works fine on the ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Exploring MongoDB's dynamic Child Object access functionality in a PHP environment

How to access dynamic child objects in MongoDb using PHP In the example code below, I need to perform the same query in PHP. To get the result in MongoDb, you can use the following SHELL Script: db.getCollection('Data').find({'COLLECTION. ...

The Vue3 component fails to render after being imported through the options API

After setting up a fresh vue3 application and a vue3 module, I encountered an issue where the child components of the module were not rendering in the application. The error message "resolveComponent can only be used in render() or setup()." was appearing. ...

Is it possible for me to introduce an additional variable to the String.prototype object?

I have a question that has been bugging me out of curiosity. I was thinking about whether I can add an additional variable in front of String.prototype. For instance: $.String.prototype.functionName = function(){}; Obviously, this doesn't work as i ...

HtmlButton failing to execute client-side validation on IE11

I am encountering a strange problem with a web form using the HTMLButton in an asp.net environment. Due to formatting requirements, I need to utilize a <button> construct which functions properly in all browsers except for IE11. <button id="cmdLo ...

Encountered a 'Require() of ES Module' Error while Implementing Visx with Nextjs

Currently, I am utilizing the Visx library for chart creation within Nextjs. The scales provided by Visx are imported in this manner: import { scaleBand, scaleLinear, scaleOrdinal } from "@visx/scale" It is important to note that internally, Vi ...

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

Ways to remove a

After creating an npm link within a local dependency and then deleting that dependency from my hard drive, I am now attempting to remove this npm link. I have attempted the following steps: npm rm --global dependency npm uninstall dependency npm unlink - ...

Tips and tricks for implementing pagination with jquery and jsp

I have a JSP page where I am displaying records fetched from an Oracle database. However, I want to show only a limited number of records at a time and implement pagination using jQuery and JSP. My goal is to display 1-10 records initially, and upon clic ...