Modifications to object persist even after being reassigned

When newScore is updated, I want to make sure that oldScore remains unaffected. Can someone help with this?

newScore and oldScore are separate objects, so any changes made to one should not be reflected in the other.

To prevent updates from affecting both objects, I have used Object.assign({}, words.oldScore) to assign oldScore to newScore.

Thank you

Answer №1

When using Object.assign, it will only shallow copy the top-level object's own properties. If you need to update nested object values without affecting the original instance, you'll need to perform a deep copy instead. For more information, please visit:

MDN - Object.assign(): Warning for Deep Clone

Answer №2

[revised 2021/04/05]

In the event that words.oldScore does not include keys with values that are objects themselves, you can utilize the spread syntax to duplicate it (see code snippet).

If this condition is not met, then you will need to come up with a method to copy or clone words.oldScore. You can refer to this example for guidance.

const words = {
  oldScore: {score: 43, word: "some foo"},
};

words.newScore = {...words.oldScore};
words.newScore.word = "some bar";
console.log(JSON.stringify(words, null, 2));

Answer №3

Appreciate all of you, I was attempting to update values deeply nested within the object. The concept of "shallow copy" eluded me at first, but now it's crystal clear and I plan to delve deeper into this. Once again, thank you and have a fantastic Sunday!

UPDATE: After careful consideration (especially when speed is not critical), I opted for this solution:

var newObject = JSON.parse(JSON.stringify(oldObject));

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

Automatically conceal a div once an iframe reaches a specific height

When a user schedules an appointment on our website, it triggers a change in the height of an iframe. I want to automatically hide the section above the iframe once the iframe's height has changed. Currently, I have implemented the following code whic ...

I'm encountering an error while attempting to parse the XML file

Need help with ajax call $j.ajax({ url: "http://www.earthtools.org/timezone/40.71417/-74.00639", dataType: "jsonp", complete: function(data){ console.log(data); } }); The URL returns XML, but I'm trying to use JSONP to avoid cross-site s ...

Creating dynamic forms and tables on an HTML webpage

I'm struggling to dynamically add table elements and form elements in an HTML page. My goal is to automatically add input boxes with labels when a user enters a number in the input box without having to click any button. I believe using the 'keyu ...

Unable to utilize a variable from React Context for accessing the value within an object

I'm facing a peculiar yet seemingly straightforward issue. My object named vatRates is structured as follows: const vatRates = { "AD": 0.00, "CZ": 1.21, "RO": 1.19, "DE": 1.19, "RS": 0.00, ...

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

Using JQuery to cycle a class with a timer

My list has the following structure <div id="slider"> <ul> <li class='active'> a </li> <li> b </li> <li> c </li> <li> d </li> <li> e </li> </u ...

The attribute 'positive_rule' is not found within the structure '{ addMore(): void; remove(index: any): void;'

data() { return { positive_rule: [ { positive_rule: "", }, ], }; }, methods: { addMore() { this.positive_rule.push({ positive_rule: "", }); }, ...

How can I convert a series of numerical values into a numpy array?

Is there an alternate method to convert '1 2 3' into a numpy array [1, 2, 3] besides using np.fromstring()? Maybe through np.array() instead? Appreciate any insights. Thanks! I attempted the following: x = '1 2 3' x = np.fromstring(x, ...

Having trouble with Javascript fetch() not receiving the correct JSON data from the local server

My Django backend is serving JSON data, but I'm encountering some unexpected results. When using curl 127.0.0.1:8000/posts/, the response includes: [ { "title": "This is a title", "body": "Body :)", "pub_da ...

JavaScript function to identify and highlight duplicate values within rows

In my current project, I am utilizing JavaScript to identify and highlight duplicate values within a table. The functionality of the code involves storing table row values in an array, checking for any duplicates, and then highlighting those rows accordin ...

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

What is causing the Angular-UI TypeAhead code to display all items instead of filtered items?

I have been experimenting with the angular-ui typeahead directive to create a filtered input box that only shows items based on what has been typed. However, my current code is displaying all the items instead of just the filtered ones. If you'd like ...

Having issues with loading THREE.js object within a Vue component

I'm baffled by the interaction between vue and THREE.js. I have the same object that works fine in a plain JS environment but not in vue.js. The canvas remains empty in vue.js and the developer console displays multiple warnings. The code I used in J ...

Leveraging jQuery's Append functionality

Struggling with using jQuery's .append() method. Check out my code: $('#all ul li').each(function() { if ($(this).children('.material-icons').hasClass('offline-icon') == false) { $('#online ul').append ...

Ensure that test cases in Angular2 include a line that covers conditions for returning values

I'm having trouble implementing test coverage for an online platform, as I'm not sure how to approach it. Within my service method, I have the following code: public getResults() { return this.http(url,body).map(this.mapResponse); } private ...

What is the best way to centralize the storage of my website's header and footer?

Constantly updating headers and footers requires me to manually transfer the code to each web page every time, which is not the most efficient method. I'm considering using a "header" and "footer" div, and using jQuery's $(document).ready functio ...

"Compactly condensing" an abundance of boolean values in JSON through manual effort

We are dealing with a data model that consists of 600 boolean values per entity. This entire dataset needs to be transmitted from a node.js backend to an Angular frontend via JSON. Considering the internal nature of this API (not public), our primary focu ...

Looping through color transitions upon hover using CSS

I am trying to create a color transition effect on hover, where the background changes from yellow to red and then back to yellow in a loop. I'm having trouble figuring out how to make this transition repeat continuously. Do I need to incorporate Java ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...

ReactJS - Element not specified

I'm experiencing a specific issue with the component below related to the changeColor() function, which is triggering an error message: TypeError: Cannot set property 'color' of undefined This error seems to be isolated within this compo ...