Deleting objects from a referenced array in JavaScript

I'm running into an issue where my req.query data is unexpectedly changing. I initially set it with several key-value pairs, but when I check the values at a later point, only one key remains. It's puzzling why this is happening.

var req = {};
req.query = {
    url: 'https://google.com/',
    width: '500',
    height: '190',
    ref: 'http://domain.tld',
    rnd: '9314871930982'
};
var data = req.query;
delete data.width;
delete data.height;
delete data.url;
delete data.ref;

console.log(req.query);
console.log(data);

Answer №1

When utilizing the following code:

var data = req.query;

you are essentially creating a reference to the same object that req.query is referring to.

+-----------------+                     +----------------------------+
|      data       |====================>| url:'https://google.com/'  |
+-----------------+                     | width: '500'               |
                                        | height: '190'              |
+-----------------+                     | ref: 'http://domain.tld'   |
|    req.query    |====================>| rnd: '9314871930982'       |
+-----------------+                     +----------------------------+

This means that any modifications made to the object through either data or req.query will impact all other references to it as well. In essence, it's like accessing the same object using two different names.

Upon inspecting your code, if you remove elements from data, you are effectively removing them from the object referenced by req.query.

If this is not the desired outcome, you will need to create a clone of req.query using one of the methods outlined in this particular thread.

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

Pedaling through an array of elements

I recently tackled a project involving the creation of traffic lights that cycle upon clicking a button in HTML. However, when I tried to do the same with a text list, it just doesn't seem to work. The objective is to cycle through the list of individ ...

Navigating through a jQuery array while utilizing the $.inArray method

Below is an example of my Array that I am working with, retrieved from a successful jQuery .post call: data = JSON.parse(data); $(".chk_permission_").each(function() { if ($.inArray($(this).val(), data)) { $(thi ...

When tapping on grid items in the Safari browser using React Material-UI, they mysteriously switch positions

I've encountered an issue with grid Items in my React MATERIAL-UI project, specifically in the Safari browser. The problem does not occur in Chrome or Firefox. Within the grid, there are checkboxes that move from one place to another when clicked, a ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

Saving and accessing an array using a PHP cookie

I would like to create a system for storing information from virtual index cards. Each card will have a front and back side, and users can store multiple cards, with data on each side. I ----------------- I I CARD 1 FRONT I I------------------I I -------- ...

Embedding an Angular function within a JavaScript function

My AngularJS dialog is defined in the angular-app.js file like this: angular.module('myAPP', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) { $scope.status = ' '; $scope.showAdvanced = fu ...

Employing a while loop to cycle through a character array passed as an argument in the C programming language

I've been grappling with an issue in C as I am still relatively new to it. The problem at hand involves iterating through a char array that is passed as a parameter. The array in question was created as a String literal and supplied as an argument. My ...

When feeding a valid JSON to Datatable, it unexpectedly displays "No data available in table" instead of populating

I have been attempting to initialize data tables and provide it an array of objects. However, I keep encountering an error message stating that there is No data available in table. Surprisingly, when I check the console output, it clearly shows that this i ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

I encountered a TypeError when trying to create a jQuery plugin after I made changes to the String

When attempting to create a jQuery plugin after modifying String.prototype, a TypeError may be encountered. This raises the question of whether this is a bug in jQuery. The issue arises with function ordering and now it is necessary to prioritize creating ...

Requests exceeding 8 kilobytes

I am looking to measure the round trip time between a client and server. Users have the option to determine the size of the request/response message they want to send. On the client side, I am using the Ajax-Post method to transmit 100 messages every 100 m ...

Ways to display closing tag in minimized code in JavaScript documents

I am encountering an issue where the closing tag of folded code is visible in my HTML file, but not in my JS files (specifically JSX syntax). I apologize if this is a trivial question, but I am hopeful that someone can assist me in making the closing tag ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Issue: "fourSquareService.retrieveLocations does not exist as a function"

Struggling with AngularJs - How to Utilize Factory Alongside Form Input in URL for Data Fetching? This is my first time asking a question here. I've been diving into Angular and wanted to organize my services by separating them into different files. ...

Tips for dynamically updating the value of a variable in Vue by importing a JavaScript file

There is a file for an app that imports ymaps.js where YmapsComponent.vue is declared. import '../js/ymaps.js'; import { createApp } from 'vue'; const app = createApp({}); import YmapsComponent from './components/YmapsComponent.vue ...

Keep the division visible once the form has been successfully submitted

Initially, I have created 3 divs that are controlled using input type buttons. These buttons serve the purpose of displaying and hiding the hidden divs. Within these divs, there are forms to store data. Currently, my goal is to ensure that the div that was ...

Seeking specific parameter in a JSON array using JavaScript: A guide

Currently, I am working on a project that involves retrieving Facebook news feed data using the graph API. Upon receiving the JSON object, I display it on the page. The "Likes" section is presented as an array of JSON objects like this: data.likes: { ...

F# is giving an error message about a mismatch in data types between an array and an

I've recently started working with F# and I have a function where elements are added to an array like so: let mutable result = Array.CreateInstance(typeof<int>, arrayA.Length + arrayB.Length) .... result.SetValue(arrayA.[iidx], kidx) .... It s ...

The functionality of the Bootstrap dropdown or radio input type is not functioning correctly

I'm currently utilizing electron([email protected]) along with bootstrap([email protected]). Whenever I attempt to incorporate a dropdown or other components from Bootstrap, they simply do not function. I am unsure of what mistake I might ha ...