Deleting a key from one object will also remove that key from another object - JavaScript

I have come across an interesting issue with my Javascript code. I am working with two objects, dict1 and dict2, where I need to maintain a form of state and then post the final object.

When I click on certain buttons, I assign dict1 to dict2. However, when I try to delete a key in dict2, it also removes the key from dict1, which is not what I intended. Below is my code snippet:

dict1 = {
    123:{
    456:2
  }
}

dict2 = {}

dict2[123] = dict1[123]


delete dict2[123][456]


console.log(dict1)

// It logs {123 : {} } whereas dict1 should remain unchanged

It appears that the objects are being shallow copied somehow.

Answer №1

To avoid modifying the original object, utilize the spread operator (...) to create a "duplicate."

Initially, when you copied the reference from dict1[123] to dict2[123], both dictionaries pointed to the same object. This meant changes in one dictionary reflected in the other. By using the spread operator, all contents are added to a new object. As a result, dict1[123] and dict2[123] hold different references with the same data, allowing for independent modifications.

Learn more about the spread operator here.

dict1 = {
  123:{
    456:2
  }
}

dict2 = {}

dict2[123] = {...dict1[123]}

delete dict2[123][456]

console.log(dict1)
console.log(dict2)

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

Adding an event listener to detect left or right mouse clicks - using onclick doesn't capture right clicks

I'm currently in the process of applying for an Internship through this Internship Link One thing that caught my attention right away is the issue with uploading or pasting a cover letter. When attempting to upload or paste a cover letter, it redirec ...

Checking for equality between two JSON objects using Express JS

I have a question regarding my code using expressjs. I am attempting to compare two JSON objects and if they match, I want to increment a variable that was previously defined. Can you please help me identify any errors in my code? app.get('/comp&apos ...

What is the best way to eliminate duplicate values within a v-for array?

To eliminate duplicate values, I wrote the following code: vue <div class="col-md-6" style="float: left"> <ul class="list-group"> <li class="list-group-item" :class="{ active: ind ...

Tips for adjusting image size to take up only half of the screen in NextJS

Struggling to resize an image to fit only 50% of the screen in NextJS? The Image component provided by NextJS comes with its own inline styling, making it tricky to customize. Currently, I attempt to style the image by wrapping the Image component in a spa ...

Creating an animated time-based scrollable bar chart in javascript

As someone who is new to JavaScript and charting, I am seeking assistance with a specific task. Despite browsing various JavaScript charting libraries and examples, none seem to address my issue: My goal is to generate dynamic stacked bar charts, as depic ...

In Typescript, convert an object into a different type while maintaining its keys in the resulting type

Imagine you have a code snippet like this type ResourceDecorator = (input: UserResourceDefinition) => DecoratedResourceDefinition const decorate: ResourceDecorator = ... const resources = decorate({ Book1: { resourceName: 'my-book', ...

Manipulate the color of the parent text using a button nested within

I am working on a script that adds a button to div elements with the class name "colors". When the button is clicked, the text color of the parent element will change to a specified color. However, I'm facing an issue where it only changes the last el ...

Ways to trigger the upgradeneeded event in IndexedDB without upgrading the version

Can you help me understand the "upgradeneeded" event? I want to be able to check the database every time a user reloads the page. Is there a way to trigger this without actually upgrading the version of the indexedDB? request.addEventListener('upgrad ...

Utilizing .isDisplayed() in conjunction with .each() in ProtractorJS for Angular: A guide

Currently, I am working on setting up a test within my Angular application. The goal of this test is to click on an element and check if a specific object is displayed. While I believe the code provided below should work, I am aware that the isDisplayed( ...

The performance of Google Maps API is compromised by a high number of markers,

Currently, I am facing a challenge with loading approximately 600 Google Map markers on page load using the addMarker function. The loading time for the page is quite long. Is there any way to optimize the loading speed while still utilizing the addMarke ...

Creating an object using JSON and implementing custom methods in Javascript

When making a $.ajax request to an API, I receive a chunk of JSON data. The JSON looks something like this: var result = { "status": 200, "offset": 5, "limit": 25, "total": 7, "url": "/v2/api/dataset/topten?", "results": [ { "d ...

How to use PHP and JavaScript to update a location marker on Google Maps

I'm new to web development and in need of some help, please. I have a code that is supposed to update the marker location with coordinates retrieved from a database. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AP ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...

Form validation displaying only the initial error message

When validating a form, I am encountering an issue where only the first error message can be displayed: ContactUs.prototype.desktopErrors = function(){ var THIS = this; THIS.$el.find('#submit').on('click', function(){ ...

JQuery computes the grand total without displaying it on the screen

I have been working on creating a small e-commerce website, and recently integrated a jQuery program to calculate items in the shopping cart. I wanted to display the total amount of these items next to the cart, but despite seeing that the calculation was ...

What is the best way to exclude HTML tags from the innerHTML attribute?

Currently, I am in the process of developing a messenger application and facing an issue where my messages are not ignoring HTML tags. This is happening because I directly paste the input text into the innerHTML of the message. The code snippet responsible ...

How can I retrieve and store session information during the authorization event in Socket.io with express-sessions?

I have set up a websocket using Socket.io and the express 4 framework on a node.js server. Currently, I am working on implementing an authorization step for my users when they are using the websocket. Upon a user connection, a token is passed as a query ...

Is there a way in Bower to automatically select only CSS or JS files from an open source project, rather than both, if that is my preference?

Although I suspect the answer, imagine I desire to incorporate the CSS from Twitter Bootstrap without the Javascript. I've set up a gulp script to extract everything from my bower.json file, minimize the JS, compress the CSS, and transfer it to my de ...

What is the preferred method for accessing nested object properties in React props?

Building upon a previous inquiry - Javascript - How do I access properties of objects nested within other Objects It appears that standard dot notation doesn't suffice for accessing nested object properties within React state/props. In the case of t ...

Why is it necessary for me to utilize JSONP?

What is the significance of using JSONP? A few days ago, I inquired about not receiving a response from a rest server while using jQuery. It turns out that I need to utilize JSONP. I tested this on my own server and it was successful. Now, I am tasked wi ...