When I use the shift method on one array, it alters the contents of that array

I am encountering a peculiar issue with two arrays of objects in my program. One array is named "Responses" and the other is called "Questions." The problem arises when I remove the first element from an object in the "Questions" array using shift() method. Surprisingly, the second array "Responses" also gets affected even though I haven't explicitly called shift() on it. Below is the snippet of code causing this behavior:

private async Sousstep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> {
    const siteDetails = stepContext.options as SiteDetails;

    // Logic goes here...

}

Answer №1

DB.query().then((result) => { Questions = result; Responses = result ; 
console.log(Responses[0].subquestions)})

By using the code above, both Questions and Responses will reference the same memory location. Any changes made to one will affect the other.


DB.query().then((result) => { Questions = JSON.parse(JSON.stringify(result)); 
Responses = JSON.parse(JSON.stringify(result)) ; console.log(Responses[0].subquestions)})

This method based on JSON will generate new instances, ensuring that you are not altering the original array. However, it may be slightly slower. Additionally, if your array objects contain functions or symbols as properties, this approach may not be ideal (as these are not valid JSON values).

If you prefer using a module, consider utilizing lodash. Simply import it and use:

DB.query().then((result) => { Questions = _.cloneDeep(result); 
Responses = _.cloneDeep(result); console.log(Responses[0].subquestions)})

You also have the option to create your own custom function for this purpose.

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

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Is there a way to eliminate the button?

My button is named "String A". String A = myButtonName; If I want to remove the button, using: layout.removeView(myButtonName); This method won't work with a string. Is there a way to do it? Currently, trying to use the string directly gives a ...

Action of Submit Button Based on Field Matching Another Form

I currently have a single page that contains two forms, with only one form being displayed at the moment. The concept is that if the user selects a specific state from the drop-down menu and clicks on the submit button, they will be redirected to either a ...

Setting up the data for the AjaxAppender Request Log4Javascript

I am completely new to Log4Javascript and the concept of logging, so please bear with me. My current task involves sending logs to a CouchDB server using a POST request. However, I keep encountering an error from the server: {"error":"bad_request","reaso ...

What is the best way to create a promise in a basic redux action creator?

My function add does not return any promises to the caller. Here's an example: let add = (foo) => {this.props.save(foo)}; In another part of my application, I want to wait for add() to finish before moving on to something else. However, I know t ...

Using jQuery to generate nested lists

I have attempted various solutions for creating nested ul/li elements without success. I am a beginner in JavaScript and struggling with this task. The data is retrieved after the page has loaded, and it looks like this: data = { "key1": ["value1", va ...

Tips for exporting a React Component without using ownProps in a redux setup with TypeScript

I'm currently working on a project using typescript with react-redux. In one of my components, I am not receiving any "OwnProp" from the parent component but instead, I need to access a prop from the redux state. The Parent Component is throwing an er ...

What causes nodejs to exit prematurely without running all the code?

When running the code provided, it randomly prints "DONE" or not. Can you explain why this happens? How can I ensure that it always reaches the console.log("DONE"); line every time? const {Worker, isMainThread, parentPort} = require('node:worker_threa ...

Repeated URL causes Node to redirect

I am currently working on a project that involves redirecting users if they enter a specific URL, especially for redirecting from a Heroku domain. During my testing phase on localhost, I noticed that the redirect URL keeps getting repeated: http://localh ...

Implement a functionality to retrieve uploaded files by utilizing the onChange event of a

I'm currently working on converting this jQuery code to React: //Js $(".custom-file-input").on("change", function() { var files = Array.from(this.files) var fileName = files.map(f =>{return f.name}).join(", ") $( ...

Uncertainty surrounding the inherited styling of an element in HTML

I am seeking clarification on the distinction between two methods of writing HTML code: CSS file (applies to both the first and second way): .parent{ color:red; font-style: italic; } .child_1{ color:blue; } .child_2{ color:green; } First approach ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

Concluding the use of angular-bootstrap-datetimepicker when selecting a date

I am currently utilizing the UI Bootstrap drop-down component to display the angular-bootstrap-datetimepicker calendar upon clicking. Although it works well for the most part, I have encountered an issue where the calendar block does not close when clicked ...

When using Stripe checkout, the database IDs are altered, causing issues when trying to delete or update stock in the database using a webhook

I have been working on developing an ecommerce platform using NextJs, Sanity as the CMS, and Stripe as the payment gateway. However, I have encountered an issue during the checkout process. When creating the checkout session, Stripe seems to alter the prod ...

The functionality of Bootstrap tabs is compromised when used within a modal dialog

I am encountering an issue while using Django and Bootstrap to implement nav-tabs within a modal that is displayed upon clicking a button. The problem lies in the fact that when a tab is clicked, its content does not appear. Below is a basic example: {% ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

What is the best way to adjust the spacing between components to prevent overlapping?

I'm looking to adjust the spacing between the textfield and button components so they don't overlap. I want to create some space between them but I'm not sure how to achieve this. I'd like to have at least 1-2 spaces added between the ...

Utilize a button to apply styles to a Span element dynamically generated with JavaScript

I am attempting to spin a span generated using JavaScript when a button is clicked. The class is added to the span, but the spinning effect does not apply. <p>Click the button to create a SPAN element.</p> <button onclick="myFunction ...

Delete items recursively in a dynamically changing JSON dictionary or list based on a condition for names that are not present in a specified list using

Looking to clean up a file by removing keys not in the specified "keep-list". Any suggestions on the best method for this? Check out an example below: {"address":"item/address","data":{"set1":{"sub_ref1":0,"sub_ref2":1550620800,"sub_ref3":false,"sub_ref4" ...

Encountered a Swift 3 error stating: "The argument labels '(named: _, _:,_:)' do not match any available overloads" when attempting to populate a UITableView with an array of UIImage

I'm encountering an issue when attempting to load an array of images into a UITableView using a prototype cell in a separate view controller. Unfortunately, I didn't receive a helpful response from my post on this thread about a Swift 3 error re ...