Ways to connect the value of one variable to multiple others

I am trying to work with two variables: masterdata and datatoedit. The masterdata variable contains an array value, while datatoedit holds an object value.

My goal is to copy the first data element from masterdata into the variable datatoedit, so I attempted the following code:

this.datatoedit = this.masterdata[0]

However, when I make edits to the data in datatoedit, the data in masterdata[0] also changes.

Is there a way to prevent changes in datatoedit from affecting masterdata[0]?

Answer №1

To create a duplicate of an object, utilize the Spread syntax in ES6:

this.updatedData = {...this.originalData[0]}

Answer №2

One potential issue with the approved solution is when the masterdata objects contain nested objects like:

{
   name: 'John',
   age: 30,
   address: {
       street: 'ChurchStreet',
       city: 'Bangalore',
       state: 'KA'
   }
}

    var masterdata = [
        {
            name: 'John',
            age: 30,
            address: {
                street: 'ChurchStreet',
                city: 'Bangalore',
                state: 'KA'
            }
        },
        {
            name: 'Jane',
            age: 26,
            address: {
                street: 'West of Chord',
                city: 'Mumbai',
                state: 'MH'
            }
        }
    ];

    // Using the spread operator
    var datatoedit = {...masterdata[0]};
    datatoedit.age = 32;
    datatoedit.address.street = 'Infantry Road';

    console.log('Using the spread operator');
    console.log('masterdata[0]: ' + JSON.stringify(masterdata[0]));
    console.log('datatoedit: ' + JSON.stringify(datatoedit));


    // Using Object.assign()
    datatoedit = Object.assign({}, masterdata[0]);
    datatoedit.age = 35;
    datatoedit.address.street = 'Brigade Road';
    console.log('Using Object.assign()');
    console.log('masterdata[0]: ' + JSON.stringify(masterdata[0]));
    console.log('datatoedit: ' + JSON.stringify(datatoedit));


    // Applying JSON.parse() and JSON.stringify()
    datatoedit = JSON.parse(JSON.stringify(masterdata[0]));
    datatoedit.age = 35;
    datatoedit.address.street = 'West of Chord Road';

    console.log('Using JSON.parse() and JSON.stringify()');
    console.log('masterdata[0]: ' + JSON.stringify(masterdata[0]));
    console.log('datatoedit: ' + JSON.stringify(datatoedit));

 

It's worth noting that when dealing with nested objects, both the spread operator and Object.assign() may not work as expected due to shallow copying.

By employing a combination of JSON.parse() and JSON stringify(), a proper deep copy can be achieved, ensuring correct behavior in all scenarios (even though these functions are not specifically designed for deep copying).

Answer №3

An alternative method is to utilize the lodash function clonedeep, which ensures that no references are copied.

updated_data = _.cloneDeep(primaryData[0])

You are free to make any desired modifications to the updated_data.

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

Arranging serialized information from a tabular format and retrieving specific data

: I'm currently attempting to utilize an AJAX POST request to send data from a dynamic webpage that includes information gathered from a table form, a date selection box, and comment text input. The webpage is generated as a PHP file on a GET request ...

Injecting windows in Angular

Is there a way to prevent the Angular instance from injecting into the global (window) scope when required and bundled with webpack or any other module bundler? Upon inspection, I discovered that the current main Javascript file in the Angular npm package ...

Is there a way to achieve a similar outcome on my site?

Recently, I noticed a mouse-hover effect on two websites and found it quite appealing. https://i.sstatic.net/Ly0gP.png https://i.sstatic.net/oDe1i.png This is the specific effect that caught my attention. Can anyone provide me with insight on how to impl ...

Issue encountered when trying to attach a hover event to the items in a comb

Currently, I am facing a specific situation. The requirement is to display a custom tooltip when the mouse hovers over the combobox items (specifically the "option" tag). Initially, my solution involved using the title tag. While this method worked effecti ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

What is the process for sending a request to a static resource along with parameters?

I currently have a node.js restify server running, along with a folder containing static resources. const restify = require('restify') let server = restify.createServer() server.listen(8080, function () { console.log('%s listening at ...

Accessing the chosen value of an ng-model

Currently, I'm attempting to refine some search results by utilizing the chosen value from an ng-select element (stripping away unnecessary formatting and details). Here's what I have so far: <select ng-model="medium" ng-options="medium as me ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

I am endeavoring to send out multiple data requests using a function, ensuring that the code execution occurs only once all the results have been received

After reading through a post on Stack Overflow about handling multiple AJAX calls in a loop (How to take an action when all ajax calls in each loop success?), I was able to come up with a solution. I decided to track the number of requests I needed to make ...

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Difficulty encountered when applying date filtering on a specific filter in the MUI-DataGrid

Software Version: "@mui/x-data-grid": "^6.2.1" I have a script that generates columns for the DataGrid as shown below (only including relevant code) if (prop === "date" || prop === "dateModified" || prop === "n ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Is there a way to randomly rearrange an array of objects when the page loads, then iterate over the rearranged array without triggering a console warning about "two children with the same key"?

When shuffling the array and mapping over it in my application, I am able to correctly display the shuffled data using translate3d for a slider effect. However, I keep receiving a growing list of console warnings: "Encountered two children with the s ...

What techniques can be used to maintain the value of 'this' when utilizing async.apply?

Employing async.parallel to simultaneously run 2 functions, initiated from a static function within a mongoose model. In this code snippet (where the model contains a static function named verifyParent), I utilize this to access the model and its functions ...

Template displaying multiple polymer variables side by side

Here is the date object I am working with: date = { day: '05' } When I use this code: <div>{{date.day}}</div> It generates the following HTML output: <div>05</div> Everything looks good so far. Now, I want to try th ...