Replicating JavaScript Objects

Could someone shed light on the reason behind obj displaying as {a:2} rather than {a:1} in this scenario?

var obj = {a:1};
var data = {b:obj};
data.b.a = 2;

console.log(obj); // {a:2}

Answer №1

When working with objects in JavaScript, it's important to remember that they are referenced values. This means that when you change one reference, all other references to that object will also be affected. To avoid this issue and create a completely separate copy of the object, you need to make a deep clone.

To create a deep copy using jQuery, you can use the following method:

// Deep copy
var newObject = jQuery.extend(true, {}, obj);

If you're wondering why I recommend using jQuery for this task, you can read more about it here: What is the most efficient way to deep clone an object in JavaScript?
(Answer provided by John Resig on Stackoverflow)

Answer №2

Instead of duplicating objects, you are creating new references to the existing variable in this scenario. Both data.obj.a and obj.a refer to the identical memory location. The value 2 is assigned to this memory location on Line 3.

For a thorough cloning process, consider the following method:

var data = JSON.parse(JSON.stringify(obj));

Answer №3

For those using a browser derived from NS like FF:

var data = { b: eval ( obj . toSource ( ) ) } ;

or

var data = { b: eval ( uneval ( obj ) ) } ;

If not using an NS derived browser:

Object . function . deepClone = function(){ 
/*
     It can be quite complex to handle objects like:
              animal=123; animal.beastly=432;                                        for example, object "overloading"
              monster = new ( function ( ) { this . this = this } ) ( )            for instance, self-referential / recursive
      Note: JSON cannot handle these types but toSource () can manage recursive structures
      alert ( new ( function ( ) { this . this = this } ) ( )  . toSource ( )  );
                                                                                                                       for example    #1={this:#1#}
      alert ( new ( function ( ) { this [ this ] = this } ) ( )  . toSource ( )  );
                                                                                                                   for example     #1={'[object Object]':#1#}
      alert ( new ( function ( ) { this [ this . toSource ( )  ] = this } ) ( )  . toSource ( )  );
                                                                                                                    for example    #1={'({})':#1#}
      alert (    (     #1 = { '({})' : #1# }      )   . toSource ( )  );
                                                                                                                     for example    #1={'({})':#1#}
*/
 }

var data = { b: obj . deepClone ( )  } ;

There have been numerous attempts on SO to achieve deepClone as well as
The structured clone algorithm - Web developer guide | MDN

Hint: The Emperor is without attire

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

What is the process for accessing extra scope information with next-auth?

I have integrated next-auth with Discord authentication and included guilds in my scope, but I am unable to retrieve the guild data. How can this issue be resolved? const options = { providers: [ Providers.Discord({ clientId: process.env.DISC ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...

Android 9 encounters an error when processing a POST request in a hybrid app developed with JavaScript, Cordova, and PhoneGap

I am facing an issue with AJAX in my Android app (JS / CORDOVA). The code I am using is as follows: $.post("http://mydomain.com.br/getInfos.php" { id: id }, function(json) { if (json == "success") { alert("Success!"); } else { alert("E ...

Uh oh! An error occurred while trying to create the ngFileUpload module

After using NuGet to install Angular File Upload 12.2.13, I made sure to inject the dependencies correctly. However, despite this, I keep encountering the following error: angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module c ...

Ajax response data triggered twice

I'm struggling to understand why my data is being called twice. I attempted to replace 'append', but it's not working. I suspect the issue lies within my controller. Here is my Ajax call: jQuery(document).ready(function($) { $('# ...

What could be the reason my form inputs are not capturing any data?

I am currently working with React to build a form, but I am facing an issue. Whenever I try to type in the form fields, nothing seems to happen. Upon inspecting the state of each input in the React dev tools, I noticed that it is only capturing one letter ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Creating an Efficient Lazy Loading HTML Page with jQuery

I've been looking to create a page that loads content only as the user scrolls to that specific section, similar to the way Pinterest website functions. Does anyone have suggestions on how to design and implement this feature, or know of any plugins ...

struggling to update an array with user inputs on my to-do list app

I'm currently in the process of creating a small to-do list with some specific functionality. I want each text input (or a copy of it) to be added to an empty string, ensuring that the original input remains unchanged. The goal is to have a function t ...

Utilizing Chrome Context Script plugin to monitor page changes: A step-by-step guide

Currently, I am in the process of creating a basic Chrome extension with the purpose of removing specific DOM elements from a particular website. In my manifest.json file: { "name": "example", "version": "1.0", "description": "example description" ...

The HTML modal window is experiencing loading issues

I am attempting to implement a modal box that appears on click in an HTML document. The HTML code looks like this: <a href="#openModal">Open Modal</a> <div id="openModal" class="modalDialog"> </div> <a href="#openModal">O ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

jQuery scrollTop(0) leading to unusual scrolling patterns

Every time I click on a button, a modal window appears with a fading effect: $('.display-all-comments').fadeIn(300); $('.display-all-comments').scrollTop(0); If I remove the scrollTop(0), the scrolling works as usual. To better illust ...

Leverage JavaScript to insert the text of an HTML element attribute into another HTML element

Is there a way to access the message using JavaScript in order to write it to the heading tag? Below is my HTML code: <h1 message = "this is the title of the page"></h1> The message needs to be displayed under specific conditions. I ...

JavaScript functions not being detected by HTML - OpenLayers

As a newcomer to OpenLayers, I am facing an issue where my HTML seems to be ignoring any JavaScript function that I create. While the function works fine directly in the JavaScript document with the map, it doesn't seem to work when I create a button ...

The Angular Syncfusion schedule is unable to call upon an object that may potentially be 'undefined'

Currently, I am developing an application using Angular Syncfusion to allow users to view and book appointments. I found a helpful resource at the following link: Below you can find the code snippet I have been working on: <ejs-schedule #scheduleObj ...

Creating custom Bootstrap Card Groups by dynamically generating the specified number of cards with Angular directives

I am currently using Angular 9.1.8 for my project. For my Angular component, I have implemented Bootstrap Card Groups and Cards to display a large result set of cards in rows with more than two cards per row. Below are four example cards: <div class=&q ...

Leveraging the power of ReactJS alongside Google Tag Manager

Looking for a way to track my application using Google Tag Manager, I stumbled upon a popular package at https://www.npmjs.com/package/react-google-tag-manager. However, despite following the instructions, I am having trouble configuring it properly! Foll ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...