Make sure to push the object into two separate arrays without creating any reference

Is there a way to push an object into two different arrays without sharing the reference?
Below is the object in question:

minigroup = {
    "Id": response[0].Id,
    "MemberId": response[0].MemberId,
    "NotMemberId": response[0].NotMemberId
}

I've tried this code snippet for testing purposes:

groupCache.push(minigroup);
groupCache[0].MemberId = [0, 0, 0, 0, 0];
groupCacheOriginal.push(minigroup);

console.log("cache: " + groupCache[0].MemberId);
console.log("original: " + groupCacheOriginal[0].MemberId);

The logged results are as follows:
cache: 0,0,0,0,0
original: 0,0,0,0,0

Any suggestions on how to avoid this issue?

Answer №1

memberList.append(Object.create(newMember));
memberList[0].ID = [1, 2, 3, 4, 5];
originalMembers.push(newMember);

print("Updated List: " + memberList[0].ID);
print("Original List: " + originalMembers[0].ID);

Answer №2


groupCache.add(minigroup);
groupCache[0].UserID = [0, 0, 0, 0, 0];

var freshMiniGroup = JSON.parse(JSON.stringify(original_json));
groupCacheOriginal.add(freshMiniGroup);

console.log("cache: " + groupCache[0].UserID);
console.log("original: " + groupCacheOriginal[0].UserID);    

Answer №3

Avoid allocating memory to the object and utilize it as a function instead of an object

let smallGroup = function(){
    return {
        "Id": response[0].Id,
        "MemberId": response[0].MemberId,
        "NotMemberId": response[0].NotMemberId
    };
}

Give it a shot now

groupCache.push(smallGroup());
groupCache[0].MemberId = [0, 0, 0, 0, 0];
groupCacheOriginal.push(smallGroup());

console.log("cache: " + groupCache[0].MemberId);
console.log("original: " + groupCacheOriginal[0].MemberId);

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

Add JSON data to the div element using AJAX in ASP.NET MVC

I am successfully retrieving JSON data through an AJAX call Below is the AJAX call being made <script> $('#display').click(function () { var vacancyId = $("#vacancy").val(); var model = { vacancyId: vacancyId }; $.aja ...

What is the best way to invoke the datepicker function on all rows of table data that share the 'datepicker' class?

Hey there! I'm working with a table that features a JavaScript function for a datepicker, as well as the ability to add and delete rows. The challenge I'm facing is that each new row created has the same ID as the previous one. How can I ensure t ...

What is preventing ShowViaLink() from functioning properly in Firefox and Internet Explorer?

I am facing an issue with my webpage where the navigation does not work on Firefox or IE, but it works perfectly fine on Chrome. I suspect that the problem lies in this code, as when I made changes to it, the navigation stopped working on Firefox & IE: ...

typescript mock extending interface

I'm currently working with a typescript interface called cRequest, which is being used as a type in a class method. This interface extends the express Request type. I need to figure out how to properly mock this for testing in either jest or typemoq. ...

The functionality of reordering columns, virtual scrolling, and resizing the grid in jqgrid are not functioning properly

Implementing jqgrid with Symfony to display a datagrid has been a challenging task for me. Thanks to Oleg's insightful response, many of the major issues have been resolved. Below is a snippet of my code: <link rel="stylesheet" type="text/css" ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

CORS (Cross-Origin Resource Sharing) Request Failed

Whenever I utilize axios to send a XMLHttpRequest, an error occurs. Error: XMLHttpRequest cannot load . The preflight request is unsuccessful because there is no 'Access-Control-Allow-Origin' header present on the requested resource. Hence, acce ...

Tips for resolving the error message "cannot read property of undefined"

I've been working on coding a Discord bot and I keep encountering an error when trying to check if "mrole" has the property "app". It's not functioning as expected and I'm puzzled by why this is happening. My intention is to retrieve the te ...

Eliminate event listener using unique identifier

Is there a way to retrieve information about all event handlers for an element in JavaScript? $._data($('#element_id')[0], "events"); This will provide a detailed record of every event handler attached to the element. 0: {type: "c ...

The interlocking web of Angular dependencies

Can I begin my angular module without specific dependencies? This is my angular.module. angular.module("app", [ 'ngSanitize', 'ngAnimate', 'ui.router', 'ngMaterial', 'ngRoute', 'ngCookies', &a ...

Transferring SetState from a parent component to a child component in React Native

When working with React js, passing setState from parent components to child components is done like this. However, in React Native setABC is undefined. What is the recommended approach for achieving similar functionality in React Native? Parent.js: funct ...

Eliminate repetitive elements from an array using a specific merging algorithm

Here's a thought I have: If we have an array of objects like this: [ { "name": "Kirk", "count": 1 }, { "name": "Spock", "count": 1 }, { "name": "Kirk", "count": 1 } ] I would l ...

Top method for utilizing jQuery to locate, sift through, and implement CSS classes

Let's consider the following scenario: <span class="foo">7</span> <span class="foo">2</span> <span class="foo">9</span> We want to assign a CSS class of 'highest' to 'span.foo' with value great ...

Triggering a JavaScript function upon the alteration of a Dojo auto-complete widget's value

I'm encountering an issue with calling a javascript function when the value of a Dojo auto completer changes. Despite trying to call the function through the "onChange" attribute, it doesn't work as expected. Within the javascript function, my ...

What is the reason for not being able to initialize Strings in an array in C#?

I am working on creating a C# Class that contains a list of TV show names. I have researched the correct way to create a String array online, and it seems like I am on the right track. I am using Visual Studio 2015. However, when I hover over the String ...

The Material UI date range picker fails to close once a selection has been made

I'm currently using the Material UI date range picker, but I've encountered an issue. After selecting the dates, the date picker does not close automatically. How can I make it close once the dates are selected? I couldn't find any specific ...

Having difficulty modifying the values of my input types on the edit page

After successfully adding user values from the add user page, I encounter an issue when attempting to edit these values such as firstname and lastname on the edit page. Please review the code snippet below for any possible errors. import React from ' ...

Is there a way to make the image above change when I hover over the thumbnail?

Seeking assistance with JavaScript to enable changing thumbnails on hover. As a newcomer to JavaScript, I'm struggling to grasp how to achieve this effect. I've already implemented fancybox for gallery functionality. Below is the HTML and CSS f ...

transforming a String into a two-dimensional array in Java for use as a GameBoard

Having a String representing a Sokoban game level, each character holds a different significance: '#' = a wall '$' = the player '@' = the baggage to move '.' = the target for the baggage to reach Utilizing a ...

Cannot save PDF files to a server using jsPDF

I'm new to this community and still learning javascript & php. I am having trouble saving my PDFs with jsPDF to the local storage on the server (automatically generated). It used to work in the past, but now when I add Canvas (javascript) to my HTML, ...