Unraveling the mysteries of the spread operator in Javascript

Having trouble finding the right keyword to search for my issue, as I am confused about JavaScript or TypeScript spread operator behavior. I encountered this problem while working on a drag and drop function today, but let me provide a simple example. Imagine I have an array like this:

test = [
    {
        name: 'A',
        id: 1
    },
    {
        name: 'B',
        id: 2
    },
    {
        name: 'C',
        id: 3
    }
]

Let's say I want to create a shallow copy of this array. Initially, I did it in the following way without realizing the mistake:

My first code attempt looked like this:

const tempArray = { ...test }
console.log('check data : ', tempArray) // will result in an object instead of an array

Upon rechecking my code, I realized my error and changed it to:

const tempArray = [...test]
console.log('check data : ', tempArray) // now correctly results in an array of objects

If you can explain why both versions seem to work fine and display the same correct result, please help me identify the specific term describing this behavior so I can research further.

EDIT 1:

https://i.sstatic.net/4VawW.png

After taking another look, I see that the two methods actually produce different outcomes. The object version appears similar to an array, but it is creating an object with numbers as keys.

Answer №1

Based on my observation, it seems that you may have misunderstood the initial output.

Upon executing this code, you will obtain an object where the index of the input array serves as keys and the array values serve as corresponding values.

https://i.sstatic.net/IYkHG.png

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

Error encountered during data conversion: Unable to convert date and/or time from character string in MSSQL Sequelize

I am currently facing an issue while attempting to connect to a MS Sql server database using Sequelize and node js. When testing the post route in Postman, I encountered the following error: "Conversion failed when converting date and/or time from characte ...

[Protractor][Scroll] I need assistance with scrolling my webpage using a while loop. Could someone please help me troubleshoot the code?

When this function is called, it initiates scrolling and then pauses the browser for a 2-second period. scrollToElement(webElement: any) { browser.executeScript('window.scrollTo(0,400);').then(()=>{ console.log("sleepin ...

I am struggling to successfully read and parse a CSV file into an array

Link to my CSV file: https://drive.google.com/file/d/0B-Z58iD3By5wb2R2TnV0Rjc3Zzg/view After trying multiple references, I am still unable to properly separate the csv file by using "," as the delimiter. Is there a solution that can help me get an array s ...

Navigating through the outcomes of a database inquiry

I'm facing an issue with storing multiple rows returned by a query in the $params array. Is there a way to loop through and save each row in the $params variable? $aResult = $db->exec_sql($sql); $params = array( // where $aResult[o]'&apos ...

It is not possible to upload files larger than 4mb in ASP.NET MVC3

I am facing an issue with uploading files in ASP.NET MVC3 where I am unable to upload files larger than 4mb. I am currently using jquery.form.js for the file upload process and utilizing ajax to post the form to the server side. It works perfectly fine whe ...

What is the best way to organize objects based on their keys?

Looking to iterate through object values and append text if the key matches in JavaScript. The object is as follows: { "id": "n27", "name": "Thomas More", "className": "level-1", & ...

Using TypeScript to asynchronously combine multiple Promises with the await keyword

In my code, I have a variable that combines multiple promises using async/await and concatenates them into a single object const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([ _.zipObject( [&quo ...

Read through the text, determine the length of each word, and keep track of how

Objective: Create a JavaScript program that takes input from users in the form of several lines of text and generates a table displaying the count of one-letter words, two-letter words, three-letter words, etc. present in the text. Below is an example ou ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...

Using AngularJS to compare values against user input to determine if they are greater or lesser

When a user inputs data into an input field, it must fall within the range of values retrieved from the database. The value entered by the user should meet either the minimum, maximum, or default value obtained from the database. For instance, if the minim ...

deleting an object from an array in JavaScript

I have a collection of objects that looks like this: [{ "id": 2, "price": 2000, "name": "Mr Robot T1", "image": "http://placehold.it/270x335" }, { "id": 1, "price": 1000, "name": "Mr Robot T2", "image": "http://placehold.it ...

Navigating to the same hash using Vue Router in a consecutive manner

Currently, I am developing a website using Vue and Vue Router for routing. The method I am using to manage scroll behavior for anchor links is as follows: const router = new VueRouter({ routes, scrollBehavior (to) { if (to.hash) { ...

What is the best way to adjust the layout of these two elements using CSS in order to display them on

I need assistance with adjusting the layout of a dropdown list next to its label in an Angular html page. <div *ngIf="this.userRole == 'myrequests'" class="col-2" [ngClass]="{ 'd-none': view != 'list&apo ...

Utilize Vue JS to trigger a query when an option is selected in a drop-down select

I'm new to Vue and facing a challenge. I have multiple drop-down select menus that fetch data from an Axios request. The select only responds when I click the submit button. I want it to update when the user makes a selection from the drop-down. I can ...

How to extract a value from a span input textbox using Vue?

I just started using Vue and I'm attempting to create an auto-growing input. I've realized that it's not possible to create a real <input> element that adjusts its size based on its content and allows for value modifications using v-mo ...

Error message when converting obj to js file: Unable to locate .mtl file

I have a Python script that can convert .obj files to .json files which can be found here. I attempted to convert messi.obj to messi.js using this script, but encountered the following error message: Couldn't find messi.mtl file Why does the .mtl fi ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

`Unable to retrieve HTTP headers from PHP when using AngularJS`

My challenge lies in extracting a header from an http call in AngularJS sourced from a PHP website. The website admin assures me that CORS is enabled and the server allows JavaScript access to cookies. Here is a snippet of the code: $http({ me ...

Accessing PHP Array Elements from Another Array within a Class

Within a class, I am working with two associative arrays. My goal is to call elements from one array and use them in another "master" array. I'm wondering if this is possible or if I'm making a mistake; please keep in mind that the arrays provid ...

The data for my registration is not getting stored in the Firebase database as expected

I'm currently working on a registration app and it's my first time using firebase. My email address is successfully stored in the authentication section of firebase. However, when I try to connect my app to the database to store additional infor ...