The value of a variable undergoes a transformation following its insertion into an

During my coding tests, I came across this snippet of code:

<script>
  var newData = {}, graphs = []
  for(var j=0; j<2; j++){
    newData["name"] = 'value '+ j
    console.log(newData["name"]);
    graphs.push(newData);
    console.log(graphs);
  }
</script>

When I checked the web console, I saw the following output:

value 0 
Array [ Object ] 
value 1 
Array [ Object, Object ]

It's strange that all the objects in the arrays have the same values:

name:"value 1"

I find it puzzling because I'm not changing any values and the name is still being updated in the same loop.

I appreciate your insights on this issue!

Answer №1

Storing an object in an array in JavaScript involves placing a pointer to the object in the array, not the actual data of the object. For instance, in the provided case, a single object, newData, is created and its name property is modified within a loop. Consequently, after the loop, the newData object will have the value {'name': 'value 2'}.

Upon examining graphs[0], it will be evident that it holds a pointer to newData, displaying {'name': 'value 2'}. The same logic applies to graphs[1].

To rectify this, a new object should be created for each iteration as shown here:

graphs = []
for(var j=0; j<2; j++){
  var newData = {}
  newData["name"] = 'value '+ j
  console.log(newData["name"]);
  graphs.push(newData);
  console.log(graphs);
}

Answer №2

Please note: It is important to reinitialize the variable newData within the loop. This is because the object reference of newData remains the same, causing it to overwrite the old value with the new value each time. As a result, only the latest value will be visible.

Consider trying the following code:

<script>
    var items = [];
    for(var i=0; i<3; i++){
      var newData = {};
      newData["title"] = 'item '+ i
      console.log(newData["title"]);
      items.push(newData);
      console.log(items);
   }
 </script>

Answer №3

Shout out to deceze for the helpful response! I totally blanked on the fact that Js uses call by reference. Check out this revised code snippet:

var charts = []
  for(var k=0; k<3; k++){ 
    updatedData = {}
    updatedData["label"] = 'item '+ k
    console.log(updatedData["label"]);
    charts.push(updatedData);
    console.log(charts);
  }

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

Showing JSON data as a table in an HTML format

After receiving the JSON String from the server as a response, which can be viewed here, I've implemented the following Jquery Code: function loadCategories() { $.ajax({ type: "POST", url: "/Services/ControllerService. ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...

Acquire the jQuery cookie with the power of AngularJS

I am currently utilizing jquery.cookie v1.4.1 to set a cookie in the following manner: $.cookie('userCookie', $("#user").val()); The value returned by $("#user").val() is typically something like 'username' Now, within an angular app ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Determine the status of caps lock with a single click of a button

I am working on an application that includes a textbox and a button. I need the application to indicate whether the Caps Lock key is activated or deactivated when a user types text in the textbox and clicks the button. ...

The submission of the form proceeds even with the warning displayed

I am facing an issue with a form that consists of one text field and a submit button. The user is required to input a 3-digit number, and if the number is greater than 200, a warning should be displayed. If the user clicks OK, the form should be submitted. ...

Creating a functionality in a stack program to track the number of times an object has been shifted

Recently, I have been delving into the world of stacks and their functionality while tackling an exercise involving moving cars into a parking lot using 2 stacks to represent 2 lanes within the parking vicinity. My current code is a work in progress, but I ...

Is it possible to implement a modal within my API services?

Hello, I am in need of assistance. I am looking to display a modal every time my API returns an error. Can someone please help me figure out how to achieve this? I am currently using React hooks. const restService = (path, responseType = 'json') ...

Durable Container for input and select fields

I need a solution for creating persistent placeholders in input and select boxes. For instance, <input type="text" placeholder="Enter First Name:" /> When the user focuses on the input box and enters their name, let's say "John", I want the pl ...

RaphaelJS: Ensuring Consistent Size of SVG Path Shapes

I am currently constructing a website that features an SVG map of the United States using the user-friendly usmap jQuery plugin powered by Raphael. An event is triggered when an individual state on the map is clicked. However, when rendering a single stat ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

The unexpected occurence of the Onbeforeunload exception

I am attempting to create an exception for onbeforeunload and display a warning about potential data loss whenever the quantity is not zero: Here is what I have tried so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

Challenges with adjusting the value of HTML range inputs

Within my HTML, I have incorporated the following three elements: <button id="left" >Previous</button> <input id="animSlider" type="range" min="0" max="0" step="1" value="0" /> //THE MAX VALUE IS SET DYNAMICALLY UPON PAGE LOAD, NOT AS ZE ...

Customize a web template using HTML5, JavaScript, and jQuery, then download it to your local device

I am currently working on developing a website that allows clients to set up certain settings, which can then be written to a file within my project's filesystem rather than their own. This file will then have some parts overwritten and must be saved ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

What is the best way to transfer a value to v-model using emit?

I'm having trouble passing the selected value from a select field to v-model. Currently, the code only seems to work with a v-text-field. <script> export default { name: 'FormSelect', props: { model ...

Do we really need Renderer2 in Angular?

Angular utilizes the Renderer2 class to manipulate our view, acting as a protective shield between Angular and the DOM, making it possible for us to modify elements without directly interacting with the DOM ourselves. ElementRef provides another way to al ...

Upon initializing mean.io assetmanager, a javascript error is encountered

I am eager to utilize the MEAN.io stack. I completed all the necessary initialization steps such as creating the folder, performing npm install, and obtaining the required libraries. Currently, in server/config/express.js file, I have the following code: ...

What is the best way to retain previous values without using an object array to store values in a React state?

My approach involves storing the previous values in an array of objects, where each object represents a key-value pair. For example: [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]. However, I aim to transform ...

extract and display attribute values from a JSON array using Angular2

I'm working with Angular2 and I successfully retrieved data from Firebase using the following method: dataset: any; onGetData() { this._dataService.getAllData() .subscribe( data => this.dataset = JSON.stringify(data), e ...