Transferring Javascript properties to a new instance

In the realm of Javascript, let's consider a scenario where we have the following structure:

obj1.prop1.prop1_1.prop1_1_1 = 3;

Now, when this code is executed, the value 3 should be set in the same pathway within obj2. Essentially, it should mirror the action of:

obj2.prop1.prop1_1.prop1_1_1 = 3;

All of this needs to be done under the condition that obj2 does not initially contain prop1.prop1_1.prop1_1_1.

One approach could involve overriding obj1.prop1 so that it points to obj2.prop1. However, obj2.prop1 must also be assigned with an instance identical to that of obj1.prop1. How can we achieve this intricate task?

Answer №1

It seems like you're looking to update the property prop1_1_1 on one object and have it automatically update on another object as well.

This can be achieved using property getters and/or setters in ES5, although this approach may not be advisable.

Here's a demonstration where the getter on obj2.prop1.prop1_1.prop1_1_1 retrieves the value from obj1:

var obj1 = {
    prop1: {
        prop1_1: {
            prop1_1_1: 42
        }
    }
};
var obj2 = {
    prop1: {
        prop1_1: {
        }
    }
};
Object.defineProperty(obj2.prop1.prop1_1, "prop1_1_1", {
    get: function() {
        return obj1.prop1.prop1_1.prop1_1_1;
    }
});
console.log("obj1.prop1.prop1_1.prop1_1_1 = " + obj1.prop1.prop1_1.prop1_1_1); // 42
console.log("obj2.prop1.prop1_1.prop1_1_1 = " + obj2.prop1.prop1_1.prop1_1_1); // 42
obj1.prop1.prop1_1.prop1_1_1 = 3;
console.log("obj1.prop1.prop1_1.prop1_1_1 = " + obj1.prop1.prop1_1.prop1_1_1); // 3
console.log("obj2.prop1.prop1_1.prop1_1_1 = " + obj2.prop1.prop1_1.prop1_1_1); // 3

Live Example (view console) | Code Source

Answer №2

Assuming T.J. Crowder's theory is correct, you have the ability to perform the following actions:

obj1.prop1.prop1_1.prop1_1_1= [3]


obj2.prop1.prop1_1.prop1_1_1= obj1.prop1.prop1_1.prop1_1_1

When altering obj2.prop1.prop1_1.prop1_1_1[0], it will also impact obj1.prop1.prop1_1.prop1_1_1[0]. This occurs because when you define it as [3], an Array object is created and its reference (or pointer) is stored in obj1.prop1.prop1_1.prop1_1_1. Therefore, both obj1.prop1.prop1_1.prop1_1_1 and obj2.prop1.prop1_1.prop1_1_1 share a reference to the same array. Despite there being only one array in memory, two references exist, causing changes made to one to be reflected in the other.

If you assign obj1.prop1.prop1_1.prop1_1_1= 3, where prop1_1_1 is a primitive data type rather than an object reference, executing

obj1.prop1.prop1_1.prop1_1_1= obj2.prop1.prop1_1.prop1_1_1

results in the value 3 being copied to the other variable. Consequently, two distinct memory locations now hold the value 3, allowing modifications to one without affecting the other.

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

Looking to display the precise information from an opened Accordion in a modal window for updating purposes with Django

My main goal is to update data using a modal toggle button within a bootstrap accordion. Each question is retrieved from views.py and displayed within an accordion element. The ideal scenario is for each accordion to have a modal toggle button that, when c ...

An error has occurred in NodeJS: Value undefined is out of the acceptable range for an unspecified property in the options

I am currently leveraging worker_threads in nodejs to handle the task of reading multiple files and processing the rows for subsequent insertion into a database (using oracle-db). The volume of data I deal with is substantial, typically exceeding one mill ...

Comparing functions and function issues when using onClick in JavaScript

I have successfully created an Image Element on my web page dynamically using JavaScript. I am now trying to set an onClick event for the newly created image element. However, I am encountering a problem and I cannot figure out why?, This is the code I ...

JavaScript animation is not functioning as expected

I created a div with the id of "cen" and gave it a height and width of 50px. $(document).ready(function() { $("#cen").animate({ height: 500px, width: "500px", }, 5000, function() { // Animation complete. }); }); Unfort ...

Adding an information panel to each column in jqgrid allows the grid to display a scrolling feature

We have implemented a jQuery grid where the last column contains a link. When this link is clicked, a new panel should appear providing additional information. To achieve this, we utilized a formatter that generates a hidden div along with the link. Howev ...

VueJS Hotel Reservation Datepicker: Trouble retrieving selected check-in date using event listener

I am new to VueJS and currently working on integrating the vue-hotel-datepicker into my project. I am having trouble figuring out how to utilize the checkInChanged event listener. This is the code snippet from my template: <datepicker :startDate ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify. I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear whe ...

Avoiding triggering the parent event from the child in React

I'm facing a situation where clicking on a parent element results in it flipping to display a child element with different colors. However, the issue arises when the user tries to click on one of the colors in the child element, as it also triggers th ...

Importing or loading a JavaScript file in Vue.js is a crucial step

I'm in need of some assistance. I've been attempting to load my javascript file and listen for changes on the checkbox when it's clicked to show or hide a password. However, I can't seem to get it to work. I've tried everything I c ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

What exactly does Apple consider as a "user action"?

In the midst of my current web project, I am facing a challenge with initiating video playback after a swipe event. Despite utilizing the HTML5 video player and JavaScript to detect swipes, I have encountered difficulties in achieving this functionality. I ...

Encountering a problem with the state error while trying to modify an input field during onChange event

Whenever I pass state down from a parent component, the setState function keeps triggering an error that says setEmail is not a valid function on change event. Is there a simple solution to fix this issue? Every time I type a string into the email input f ...

How to transform a JQuery button into a dropdown menu

For inspiration, consider this JQuery UI Button example: http://jqueryui.com/demos/button/#splitbutton Now, how can you create a dropdown menu when the small button is clicked? My main concern is the way .button() alters the button's actual appearanc ...

Prioritize moving the JavaScript onload handler to the end of the queue

I am looking to include a JavaScript file at the very end of footer.php using a WordPress plugin. I attempted to do this with the 'add_action' Hook, but found that it is adding the JavaScript code near the </body> tag. add_action('wp_ ...

Subsequent calls to React's setState with an array are causing duplicate items to be appended twice

While developing a simple Twitter clone using React, I encountered a strange issue when adding a new tweet. Currently, I store a tweets array locally using the useState hook and employ setState to insert the new tweet into the array. Initially, everything ...

Using JavaScript to toggle the visibility of grids depending on the radio button choice and then triggering this action by clicking on the search button

As a newcomer to AngularJS development, I am encountering some challenges while attempting to implement the following scenario. Any suggestions or guidance would be greatly appreciated. I aim to showcase either one or two Angular UI grids based on the rad ...

When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once. HTML <!DOCTYPE ht ...

Navigating the file paths for Vue.js assets while utilizing the v-for directive

Recently, I started working with Vue.js and found it simple enough to access the assets folder for static images like my logo: <img src="../assets/logo.png"> However, when using v-for to populate a list with sample data, the image paths se ...