Modifying a JavaScript object causes changes to another object within the same array

Encountering an issue where player[0].pHand is being modified while updating player[1].pHand (where pHand is an array containing objects).

for(var j = 0; j < 2; j++){


        console.log(cardDeck[deckCounter]);

        player[0].pHand[j] = cardDeck[deckCounter];

        player[0].cardNumber ++;


        console.log(player[0].pHand[j]);

        deckCounter ++;         

    } 


    for(var k = 0; k < 2; k++){


        console.log(cardDeck[deckCounter]);

        player[1].pHand[k] = cardDeck[deckCounter];

        player[1].cardNumber ++;


        console.log(player[1].pHand[k]);
        console.log(player[0].pHand[k]);

        deckCounter ++;         

    } 

Tweaked the code slightly for clarity, having a loop for the player index instead of two separate loops. However, the issue persists with the final set of cards assigned to each player object. The console logs typically show:

Card {suit: "Heart", faceValue: "10", value: 10, played: false, img: "10Heart.png"…}

Card {suit: "Heart", faceValue: "10", value: 10, played: false, img: "10Heart.png"…}

Card {suit: "Heart", faceValue: "3", value: 3, played: false, img: "3Heart.png"…}

Card {suit: "Heart", faceValue: "3", value: 3, played: false, img: "3Heart.png"…}

Card {suit: "Spade", faceValue: "J", value: 10, played: false, img: "JSpade.png"…}

Card {suit: "Spade", faceValue: "J", value: 10, played: false, img: "JSpade.png"…}

Card {suit: "Spade", faceValue: "J", value: 10, played: false, img: "JSpade.png"…}

Card {suit: "Spade", faceValue: "K", value: 10, played: false, img: "KSpade.png"…}

Help or insights would be greatly appreciated :)

Answer №1

Javascript typically utilizes references when assigning variables, meaning that both players' pHand attributes are assigned the same cardDeck Object. For instance:

var pHand = {a:1,b:2};

var player = [];
player[0] = {};
player[1] = {};

player[0].pHand = pHand;
player[1].pHand = pHand; // we assign a REFERENCE here

console.log(player[0].pHand);
console.log(player[1].pHand);

console.log("changing value of b for player 0");
player[0].pHand.b = 3;

console.log(player[0].pHand);
console.log(player[1].pHand);
// both console logs above will be identical!

To learn "how to clone" a JavaScript object, refer to this post: How do I correctly clone a JavaScript object?

If your object is serializable (does not contain functions, only arrays and objects), you can create a simple deep copy using this method:

player[0].pHand = JSON.parse(JSON.stringify(pHand));

Full example: https://jsfiddle.net/41f07f1a/

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 Node.js callback for validating JWT tokens

In my Node.js server, I have set up an authentication route to authenticate requests: app.get('/loggedin', auth, function(req, res){ console.log(req.authenticated); res.send(req.authenticated ? req.authenticated: false) }) From what I u ...

Tips on adding several elements to an array depending on the selected value from various checkboxes?

I am working on a project where I need to populate an array based on selected checkboxes. Let's assume we have 3 arrays containing strings: const fruits = ["Apple", "Banana", "Orange", "Grapes"]; const vegetable ...

Shifting a division using insertAfter

Hey there! I'm having a bit of trouble using the insertAfter function. In each product in my store, I need to position an "add to cart" button after the price. This is the code I tried: <Script type="text/javascript" > jQuery(document).read ...

Building a NodeJS powered single page application that consumes API data

Currently, I am working on developing a single-page JavaScript web application that will periodically fetch data from multiple public and possibly private APIs. The objective is to display and update this data in various tables. I could opt for creating th ...

Use Ajax to fetch a nested PHP array in JSON format

Following an Ajax call, I am receiving a multidimensional PHP array named '$tree'. My goal is to convert this array into JSON format. Currently, my PHP page is only outputting the Array: print_r(json_encode($tree)); The success section of my a ...

The ajax request does not support this method (the keydown event is only active during debugging)

I've encountered a strange issue with an AJAX request. The server-side code in app.py: #### app.py from flask import Flask, request, render_template app = Flask(__name__) app.debug = True @app.route("/myajax", methods=['GET', ...

C implementation of insertion sort is failing to properly traverse through the array

Having trouble implementing the insertion sort algorithm in C. Can't seem to correctly traverse the array. Using the pseudocode from Cormen's Algorithms book, but still running into issues. It seems like the algorithm is skipping the first eleme ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Is it possible to utilize "this" in mapMutations spread within Vue instance methods?

Trying to define Vuex mutations like this: export default { props: { store: String }, methods: { ...mapMutations({ changeModel: `${this.store}/changeModel` }) } } Encountering an error message: An er ...

Grant permission to access a website even when domain filtering is enabled

I recently created a basic web application that utilizes the YouTube API for performing search and displaying results. $.ajax({ url: 'http://gdata.youtube.com/feeds/mobile/videos?alt=json-in-script&q=' + q, dataType: 'jsonp&apos ...

How can I toggle the radio button based on the dropdown selection?

I'm attempting to enable or disable a radio button based on the selection from a dropdown menu. View my jsfiddle example here For example, if the user selects "persons" from the dropdown, only the options for Anthony and Paul should be available to ...

Create a script that allows users to input 10 numbers, and then displays the largest number out of all the inputs

I recently wrote a program, but unfortunately, there seems to be a coding error. While the inputting part is working fine, the program is not able to find and print the greatest number. #include<stdio.h> int main() { int i, arr[10],c=0; ...

What is the best way to ensure uniform container sizes and properly align images within them?

Customize Image Sizes: Is there a way to set a standard container size and adjust image sizes properly without compromising clarity or aesthetics? The images vary in dimensions, so should they be standardized or is there another solution? Code snippet: ...

Adding a Vue component to HTML using a script tag: A step-by-step guide

Scenario: I am working on creating a community platform where users can share comments. Whenever a comment contains a URL, I want to turn it into a clickable component. Challenge Statement: I have a dataset in the form of a string and my aim is to replac ...

tips for optimizing javascript file caching

https://i.stack.imgur.com/UhWD1.pngMy web application was created using "pug" technology about 9-8 years ago, and more recently, pages have been added in an innovative framework (vue.js). However, whenever there is a transition between an old pug page and ...

The issue with json arises when utilizing $.ajax without the definition$

Attempting to make this code work properly Javascript $.ajax({ url: '/endpoint/json/', //Update the path to your JSON file. type: "post", dataType: "json", //Remove the "data" attribute if not needed. data: { ...

The straightforward onclick action only functioned once

Looking for assistance: Can someone explain why this code snippet isn't functioning properly? It seems that the increment is only happening once. var player = document.getElementById("player"); var button = document.getElementById("button"); functio ...

Running the npm install command will eliminate any external JS or CSS files that are being

For my project, I incorporated jquery-datatimepicker by including jquery.datetimepicker.min.css and jquery.datetimepicker.full.min.js in angular.json and placed them within the node_modules/datetimepick directory. Here is a snippet of my angular.json conf ...

Guide on adding user input values (type=text) into HTML using JavaScript function outcome

I'm looking for a way to use the output of a JavaScript function as the value for an input field in HTML. Currently, I have a JavaScript function that generates a random string: function generateRandomString(length) { let result = ''; ...

AngularJS: Monitoring $locationChangeStart for token verification

I am attempting to check if the next has a token or not, but it is not working and I am getting an error: TypeError: Cannot read property 'next' of undefined Any suggestions? app.js .run(function ($rootScope, $location,$log,User) { ...