Surprising outcome encountered while trying to insert an item into a list

I'm a bit puzzled by the current situation where:

let groupdetails = {
      groupName: "",
};    
const groupsArray = [];

groupdetails.groupName = 'A'
groupsArray.push(groupdetails)
groupdetails.groupName = 'B'
groupsArray.push(groupdetails)
console.log(groupsArray)

The outcome I am seeing is:

[ { groupName: "B" }, { "groupName": "B" } ]

My expectation was:

[ { groupName: "A" }, { "groupName": "B" } ]

Not sure what mistake I might be making?

Answer №1

Remember to generate a unique reference for each element you add

let userdetails = {
      username: "",
};    
const usersArray = [];

userdetails.username = 'John'
usersArray.push(userdetails)
userdetails = {...userdetails}
userdetails.username = 'Jane'
usersArray.push(userdetails)
console.log(usersArray)

Answer №2

Having trouble understanding the concepts of Shallow Copy and Deep Copy? Check out this article.

In your situation, simply updating the value with groupdetails.groupName = 'B' does not create a new node; it still references the original one you added. To solve this, you need to create a new node using spread operator or something similar, update its value, and then push it again.

To achieve your goal, consider following the example provided below:

Answer №3

Keep in mind that Arrays and Objects behave differently when it comes to copying - objects are copied by references, not just values.

let a = 'John';
let b = a;
console.log(a === b);

When values are assigned to another variable, the original value is simply copied.

let obj = {name: 'John'};
let newObj = obj;
newObj.name = 'Kate';
console.log(newObj);  // {name: 'Kate'}
console.log(obj)      // {name: 'Kate'}

However, when an object is passed to another object, the reference is shared. Any changes made to one object will be reflected in the other.

In your scenario, this approach will work fine:

const groupsArray = [];

function addNew(value) {
    return { groupName: value}
}

groupsArray.push(addNew('A'));
groupsArray.push(addNew('B'));
console.log(groupsArray);

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

Tips for generating various series using dx-Chartjs

Trying to visualize ratings based on their type is proving to be difficult as I can't seem to figure out how to group the series according to types. The available chart options are: $scope.chartOptions = { dataSource: data, c ...

Ways to disable .animate() specifically for a particular element

I have implemented a countdown using which smoothly animates the numbers down and fades to opacity 0. Update. I have also created a demo on jsFiddle here: http://jsfiddle.net/Mw4j2/ // The .static class is added when the animation // complet ...

Is there a specific explanation as to why ng-repeat-start is not functioning properly even with the most recent version of AngularJS?

Can someone please explain why ng-repeat-start is not functioning properly despite using the most up-to-date AngularJS version? I have included it from the CDN: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></scr ...

Which HTML tags can be activated with JavaScript to be interactive?

I'm currently diving into the world of JavaScript and one of the initial code snippets I've encountered is onclick. So far, I've seen it utilized in form buttons like this: <input type="button" onclick="checkName()" value="Check name" / ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

Issues with calculating results have been identified in the Java survey program

For my project, I aim to develop a Java application that employs an array, a looping structure, and a function to carry out a survey involving 3 questions posed to 4 individuals. Each question will elicit a response of either yes or no. The final results o ...

"An error occurred with the Google chart due to 'null' not being recognized as an object, specifically in relation to the select menu and onchange event

Currently, I have implemented the following Script: <header> <script type="text/javascript" src="http://www.google.com/jsapi"></script> </header> <body> <script type="text/javascript"> google.load("visualization", "1 ...

Exploring the functionalities of the componentDidUpdate() method in React JS

In my project, I am trying to dynamically change an API parameter using a click function and render new data accordingly. The issue I encountered is that when I trigger the componentDidUpdate method with an onclick event listener, the first click works fin ...

"Troubleshooting: The Dropzone js code sample from the documentation

I am currently implementing a tutorial from the documentation provided by Dropzone.js. However, I seem to be encountering an issue as the example is not working correctly. Here is the structure that I currently have: Dropzone.options.myAwesomeDropzone = ...

Processing XML Files Using Nodejs

Apologies for the rookie question, but I'm feeling a bit confused... I'm attempting to pull "objects" from an XML file so that I can modify and incorporate them into a database. I attempted using xml2js and now have a JavaScript object, but I&ap ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

Is there a way to automatically close the Foundation topbar menu when a link is selected?

On my single page website, I am utilizing Zurb Foundation's fixed topbar which includes anchor links to different sections of the page. My goal is to have the mobile menu close automatically whenever a link inside it is clicked. As it stands now, whe ...

Add a Page to Your Domain Name using the Text Input Box

I'm looking to create an input field that allows users to enter a text string, which will be added to a domain name when submitted, redirecting the user to a specific page. Here's how the process works: The user enters 'foo' into the ...

How can I import a JavaScript file from the assets folder in Nuxt.js?

I have explored multiple methods for importing the JS file, but I am still unable to locate it. Can anyone guide me on how to import a JS file from the assets folder to nuxt.config.js and have it accessible throughout the entire website? nuxt.config.js he ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...

Module for managing optional arguments in Node.js applications

I'm on the hunt for a Node.js module that can effectively manage and assign optional arguments. Let's consider a function signature like this: function foo(desc, opts, cb, extra, writable) { "desc" and "cb" are mandatory, while everything else ...

Showing the True/False data in Material-UI Table using React

I am currently working on a Material Table event log implementation. This event log is designed to receive data in the form of 'string' and 'boolean' values. While I am able to display the string values without any issue, I am facing di ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...