Object undergoes alterations even without any direct interaction from me

Can anyone explain why the value of ColumnNames changes at the debugger breakpoint in the code snippet below? It seems to take on the same value as tempColumns after

tempColumns[k] = modi[i].data[k];
.

var addRecords= []; 
var columns = ["Column1","Column2","Column4","Column5"]
var columnNames = {};
var modi = [{
 data: {
  Column1: 'bla'
 }
},{
 data:{
  Column2: 'test'
 }
}];
var tempColumns = {};

for( var n in columns){
 var column = columns[n];
 columnNames[column] = "";
}

for(var i in modi){
 tempColumns = columnNames;
 for(var k in modi[i].data){
  tempColumns[k] = modi[i].data[k];
  debugger;
 }
 addRecords.push(tempColumns);
}

Answer №1

The reason for this occurrence is that the assignment of columnNames to tempColumns was made before your debugger. In JavaScript, object values are passed by reference, resulting in both tempColumns and columnNames pointing to the same memory location after the line:

tempColumns = columnNames

This leads to both variables referencing the same position in memory.

Answer №2

It is important to create a duplicate of the object. If you simply assign one variable to another using tempColumns = columnNames, they will both reference the same memory location. To make a true copy of an object, you can use the following method: JSON.parse(JSON.stringify(obj))

obj = {1:"hi", 2:"by"};

newobj = JSON.parse(JSON.stringify(obj));
newobj["1"] = "hello";

console.log(obj);
console.log(newobj);

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

Passing Props to a Functional Stateless Component in React

The AuthLinks component should display the notification count passed as the notificationCount prop in the Notifications Component. I need to access the notificationCount value in the AuthLinks component, but it seems like it should be available in AuthLin ...

Extracting HTML element from PHP string and placing it in a different page

In a PHP string, there is an HTML structure including a table within it: <html> <head> <!-- not much going on here --> </head> <body> <table border="0" align="center" cellpadding="0" cellspacing="10 ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

Creating a toggle button for a div element to expand and collapse its content: Step-by-step guide

For my e-commerce site selling musical instruments, I'm designing a product landing page that showcases guitars, keyboards, violins, and cellos. As part of the design, I want to include expandable sections with detailed information about each instrume ...

Sending data from JavaScript to Jade templatesIs this alright?

Utilizing node.js, express, jade, and socket.io, I have successfully executed JavaScript code on the jade side. However, I am encountering difficulty in generating HTML output from the script block. Based on your feedback, I have updated my question to in ...

Is it a good idea to resize images sourced from other websites before displaying them on your

I am currently working on a project that involves fetching images from various websites and displaying a thumbnail or resized version of the original image. Since I will be fetching many images at once, loading the original image files can take longer. ...

Incorporate innerHTML by appending instead of overwriting

Just a quick question, can we actually add content to a <div id="whatEverId">hello one</div> by utilizing: document.getElementById("whatEverId").innerHTML += " hello two"; Is there a way to INSERT content into the div without replacing it??? ...

Using jQuery to validate the existence of a link

Within my pagination div, I have links to the previous page and next page. The link to the previous page is structured as follows: <span id="previous"><a href="www.site.com/page/1" >Previous</a>. However, on the first page, there will be ...

Error: The method area is not supported for this.mesh.geometry

Recently, I've been experimenting with JavaScript, Three.js, and Leapmotion. To enhance my program, I decided to incorporate the leap widgets library which can be found here. However, after investing numerous hours into this project, I encountered a ...

Is it a common issue for a Nuxt.js page using Keycloak.js authentication middleware to reload twice when the browser window is refreshed? Also, it seems that the N

My current setup involves implementing authentication with Keycloak in a Nuxt.js middleware using the code below: import Keycloak from 'keycloak-js' const keycloak = new Keycloak({ url: 'http://localhost:8080/auth', realm: 'd ...

Exploring similarities between objects sharing identical keys within a single JSON array on Android

Presently, I have a JSON array structured like this: { "workHours":[{ "dayOfWeek":[1,2,3,4,5], "timeInterval":"00:00-00:45" }, { "dayOfWeek":[5,6,0], "t ...

Exploring the capabilities of jQuery by creating custom functions utilizing the .data method and HTML5 data

My goal is to dynamically add a new "app" to my "AppList" when a button is clicked. Javascript Solution: $(".appCreate" ).click(createNewApp); function createNewApp() { var facebookTemplate = $("#facebook-template").html(); var appName = $(this ...

Progress persists despite setbacks

Having some asynchronous code that needs to halt in case of error but continues to execute: async saveCoupons({ state, rootState, dispatch, commit }) { const promises = [] state.userCoupons.forEach(coupon => { if (coupon.isNew &&am ...

Utilizing jQuery to implement a function on every individual row within a table

I have a collection of objects that requires applying a function to each item, along with logging the corresponding name and id. Below is the snippet of my code: var userJson = [ { id: 1, name: "Jon", age: 20 }, { ...

How can we make the lines in the Highcharts force plot take up all the available width

Our design team has specifically requested that our stacked area charts fill 100% of the chart width, instead of stopping at the tick marks. To illustrate this, they have provided a mockup: View Mockup Currently, our chart does not extend to the full wid ...

Guide to incorporating third-party JavaScript files and functions into my Angular web app

I have been trying to integrate external code (HTML, JS, and CSS files) into my Angular web application. Within this external code, the structure of the HTML file is as follows: index.html <html> <header> </header> <body> </bo ...

I'd like to know how to retrieve the start and end dates of a specific month using JavaScript

How can I retrieve the start and end date of the current month? const currentDate = new Date(); const startOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); const endOfMonth = new Date(currentDate.getFullYear(), currentD ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

What is causing this issue with my jQuery UI animation?

Below is the HTML code snippet: <div id="menu_status_item"> <span class="menu_status_bar"></span> </div> Here is the CSS code: #menu_status_item { margin-top: 40px; width: 100%; } .menu_status_bar { margin-le ...

Uncertain entities in Typescript

I used to use Flow for typing. How can I type an imprecise object? Here's the array I'm working with: const arr = [ {label: 'Set', value: setNumber, id: 'setNumber', set: setSetNumber, type: 'text'}, ...