Tips on connecting properties of two individual JavaScript objects

Within my angular service, I have two objects with a property named nodes that I want to point to the same array. However, when I make changes to the nodes in one object, it does not reflect on the other. Here is how I am attempting to achieve this:

objectOne.nodes = [o1, o2, o3];
objectTwo.nodes = [];
angular.forEach(objectOne.nodes, function(n){
    objectTwo.nodes.push(n); // Some logic assigns nodes from objectOne to objectTwo
})

I expect changes made to objectTwo.nodes[i] to be reflected in objectOne.nodes[j], given that i and j are indices of the same node in the two different objects (assuming the order may differ). Unfortunately, this does not seem to work as intended. Is there an error in the way I push nodes into objectTwo?

For context, I am modifying the objectTwo node directly within the DOM. Both objectOne and ObjectTwo exist as variables in memory within my service.

Answer №1

When you push the same reference of the object, any changes made to the new array will also impact the original source.

var obj1 = {}, obj2 = {}, obj3 = {};

obj1.nodes = [{ id: 1, name: 'o1' }, { id: 2, name: 'o2' }, { id: 3, name: 'o3' }];
obj2.nodes = [];
obj3.nodes = [];

obj1.nodes.forEach(function (o) {
    o.id % 2 ? obj2.nodes.push(o) : obj3.nodes.push(o);
});

obj2.nodes[1].name += '+';

console.log(obj1);
console.log(obj2);
console.log(obj3);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Need a hint :

let newDiv = document.createElement("div");
let obj1 = {}, obj2 = {};
obj1.elements = obj2.elements = [];
obj1.elements.push(newDiv);
newDiv.style.color = "blue";
console.log(obj1.elements[0].style.color);
console.log(obj2.elements[0].style.color);
newDiv.style.color = "red";
console.log(obj1.elements[0].style.color);
console.log(obj2.elements[0].style.color);

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

Utilizing Vue.js to display raw HTML content in elements.io table

I am trying to display HTML data in a table using Vue.js. new Vue({ el: "#app", data: { todos: [ { text: "<p>Learn JavaScript</p>", done: false }, { text: "<p>Learn Vue</p>", done: false ...

How can one access a dynamically generated element in Angular without using querySelector?

Currently in the process of developing my custom toastr service, as shown in the GIF below https://i.sstatic.net/Zpbxs.gif My Objective: https://stackblitz.com/edit/angular-ivy-tgm4st?file=src/app/app.component.ts But without using queryselector. It&apos ...

What could be causing the PAGE CSS to malfunction?

I am looking to export HTML text as a word document with A4 size and portrait orientation. My JavaScript currently allows me to export the text, but it appears like a webpage format rather than in A4 or portrait mode. I have tried adding @page CSS styling ...

Can the Browser width/document width be maintained when shrinking the browser window size?

https://i.stack.imgur.com/a4gfA.pngLooking for a solution to maintain the browser/document width at 350px, preventing users from minimizing the window. The desired width is actually 400px, not 350px. Please refer to the image above. I require the window ...

I am experiencing difficulties with ng-animate not functioning properly on the Android WebView of my Samsung Galaxy S4

Implementing an animation with ng-animate for a button in an Android hybrid app using WebView. The animated button code is as follows: <div class="dish-like dish-like-animater"> <img ng-hide="page.liked" class="dish-like-unliked" src="http: ...

I'm having trouble with my React Router Dom Redirect path. Everything seems to be set up correctly, but for some reason, it's not directing my home page

I have been working on adding a private route to my main dashboard, which is my home page, to make it accessible only to authenticated users. I created a new component called PrivateRoute and set up the redirection to the login page if the user is not auth ...

I encountered an error message stating "Unexpected token {" while trying to import the module "express-fileupload"

Struggling to implement file uploading with NodeJS on Ubuntu, encountering errors. Upon adding const fileUpload = require('express-fileupload'); the app fails to compile, throwing this syntax error: 2|theproje | /home/asgeir/nodejs/first_test ...

Exploring the Array Functionality in React

Is there a way to access the lista and add up all the values in unidades when the Producto matches both 1 and 2? [{ "id": "3WzFN", "cliente": "1", "lista": [{ "unidades": "2 ...

What is the process for changing the value of a specific data point within an integer array in C++ by utilizing pointers?

In my class assignment, I successfully demonstrated manipulating an array with pointers by outputting a value. However, I am now stuck on the second part of the task. The challenge involves outputting ar[0][3] using the pointer p with the given code snippe ...

Guide to importing external CSS styles into Angular 2 using the require method

I'm facing an issue with loading an external css file in different environment files. My setup includes two environments: development and production. Loading the css file locally works fine in development mode, but not in production mode. environment ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

retrieve JSON object from deferred response of AJAX request

After utilizing Ajax to send an item to a SharePoint list, I aim to incorporate the jsonObject received in response into a list of items. Located in AppController.js $scope.addListItem = function(listItem){ $.when(SharePointJSOMService.addListIte ...

Limiting the invocation of the listener method in f:ajax depending on the return value of onevent

I am looking to check if the Onevent javascript function returns true or false. My goal is to restrict the listener method call based on the return value of the Javascript function. However, the code snippet provided is causing a syntax error in Firebug. ...

Issue encountered with edges helper and a partly opaque object rendering

My goal is to create a realistic earth using three.js, similar to this example, which is an improvement from this one. However, I am facing an issue where the rendering order of the sky, earth, and atmosphere is not being properly interpreted by the render ...

Update the div each time the MySQL table is refreshed

My website functions as a messaging application that currently refreshes every 500ms by reading the outputs of the refresh.php file. I'm looking to explore the possibility of triggering the refresh function only when the 'messages' table upd ...

Developing a new class within a function

In this section of the HTML file, I have set up a form to collect email and password information from new users in order to create a new profile: <form name="userInfo"> <fieldset> <legend>Create a new account</legend> ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Is it better to use Asynchronous or Synchronous request with XMLHttpRequest in the Firefox Extension for handling multiple requests

As a newcomer to developing Firefox Add-Ons, my initial project involves calling an external API in two steps: Step 1) Retrieve data from the API. Step 2) Use the data retrieved in Step 1 to make another call to the same API for additional information. ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Filter items by nested properties in ngRepeat

Is it possible to filter a complex object with nested properties using the ng-repeat filter? Can we achieve this filtering with the ng-repeat filter provided out of the box? Data { Name: 'John Smith', Manager: { id: 123, Name: &a ...