Copying elements of an array in TypeScript

In the screenshot provided, I have the car object (unable to pretty print it here).

https://i.sstatic.net/63Y36.png

I am looking to create a function that clones one of the two elements in the factory.

My attempt at this function was as follows:

public cloneFactory(modelIndex: number, factoryIndex: number): void {
    const newFactory = this.car.model[modelIndex].factory.slice(factoryIndex, factoryIndex + 1);
    this.car.model[modelIndex].factory.push(newFactory[0]);
}

I also tried the traditional method:

public cloneFactory(modelIndex: number, factoryIndex: number): void {
    const newFactory = this.car.model[modelIndex].factory[factoryIndex];
    this.car.model[modelIndex].factory.push(newFactory);
}

The issue I am facing is that any changes made to the cloned object affect the original object as well. I cannot comprehend why the original and the clone remain linked after executing either of the methods mentioned above.

What is the correct approach to cloning an element of the array so that edits can be made later without affecting the original object?

Answer №1

When you think you are cloning an object, you may actually just be pushing a reference to the same object again. To create a true clone, you can utilize Object.assign:

const newCopy = Object.assign({}, this.car.model[modelIndex].factory[factoryIndex]);

Consider how Object.assign behaves in contrast to simply assigning a reference:

var obj = { a: 1 };
var objRef2 = obj; // Just assigns a reference; not a genuine clone
var clonedObj = Object.assign({}, obj); // True copy of `obj`
obj.a = 100;
console.log(obj.a)
-> 100 // Value changed
console.log(objRef2.a)
-> 100 // Value changed
console.log(clonedObj.a)
-> 1 // Value remains unchanged

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

Expanding the capabilities of i18next's translation function

I'm having trouble properly extending the function. I am stuck with the error Cannot redeclare block-scoped variable t. I am unsure if declaring a module is the correct approach (I am new to TypeScript). I have also tried creating a wrapper for the t ...

Assigning the size of an array using a variable

Is there a way to assign an array its size via a variable rather than a constant value? I've been attempting to do so but keep encountering the error stating "must have a constant value." int processes[] = { 1, 2, 3 }; int n = sizeof processes / sizeo ...

An array of Promise<Employee> cannot be used as a parameter for an array of type Employee[]

I am currently facing an issue with loading my Collection of Employees from a Firestore Database and fetching a 'Workday' for each Employee, which is stored as a Document in a Subcollection named 'Employees'. Below is the code snippet I ...

Parsing data from document

After reading numerous questions about working with arrays in bash, I have not found a solution to my specific issue. Currently, I have a file that includes paths to many other files. cat MyFile > ~/toto/file1.txt > ~/toto/file2.txt > ~/toto/fil ...

The outcome of the method is not being displayed

I have an issue with updating the value of an array method in an HTML file using the p tag. The problem is that even though the method returns the value, the HTML doesn't update to reflect the new value. Strangely, when using console.log, the value ap ...

In a recent C programming assignment, I was tasked with receiving input from the user for a set of 5 array elements and then transferring them to a separate array using pointers. Unfortunately, despite my efforts,

Please create a program that takes 5 integer elements of an array as input and copies them to another array using only pointers. // My unique solution #include <stdio.h> #include <conio.h> void main() { int arr[5], brr[5], *ptr1, *ptr2, i ...

Troubleshooting an Azure Web App deployment of a TypeScript Node.js application - encountering a 'service unavailable' message

I recently deployed a react-redux app on Azure using the 'Azure App Services' extension in VSCode. The project was based on the code from this repository: https://github.com/rokoroku/react-redux-typescript-boilerplate Unfortunately, when I try t ...

"Exploring How to Read Multiple Values in the Request Body Using Node.js

I am new to NodeJs development and have a question. It may be basic, but I'm not sure how to proceed. I have a task to read a request field that can contain multiple values in a JSON array like this: { "email" : "<a href="/cdn-cgi/l/email-prote ...

ngx-datatable Retrieve the most recent clicked row using multi-click mode

Currently, I am attempting to retrieve the most recent 'clicked' row from ngx-datatable. Here is what I have in my code: <ngx-datatable [rows]="rows" [selected]="selected" [selectionType]="'multiClick'" (select)='on ...

Distribute the capabilities of the class

Is there a way to transfer the functionalities of a class into another object? Let's consider this example: class FooBar { private service: MyService; constructor(svc: MyService) { this.service = svc; } public foo(): string { ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

Using malloc to handle pointers and arrays in C

I'm encountering a situation with my code that has left me puzzled. I have a basic understanding of pointer arrays, but I'm confused about their initialization process. How does this block of code function without initializing the array? Addition ...

Implementing an Angular HttpInterceptor to improve caching efficiency for simultaneous requests by utilizing a shared observable

I am looking to implement caching for HTTP parallel requests by sharing the observable and also storing the response in a Map object. Check out the online demo caching-interceptor.service.ts import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest ...

The Rx subject has not been initialized

Within this particular Namespace, I am exporting a Rx subject of the string data type: namespace something.TaskHandling { export const selectedTask$ = new Rx.Subject<String>(); Inside my TaskListComponent class within the something.TaskHandling. ...

A sophisticated method for converting a string to a number within a Typescript class without the need for a constructor?

Imagine needing to process JSON responses where all parameters are encoded as strings, regardless of their actual type. The goal is to strictly typecast these values into various Typescript classes. For example, consider the following JSON: {"id":"1","lab ...

Combining Axios with repeated promises

I am facing an issue with a loop in my GET request on the axis, and I cannot figure out why. const [ state, setState ] = useState<any[]>([]); ids.forEach((id) => { getData(id) .then((smth: Map<string, any>[]) => getNeededData ...

Issue with Material Checkboxes failing to respond correctly when their 'checked' variant is applied

In my records table, each column begins with a checkbox. When a checkbox is clicked, the record's id is stored in an array using TypeScript: onCheckboxClick(id) { if (this.selectedInvoiceables.indexOf(id) > -1) { this.selectedInvoiceables.sp ...

How to prevent value overwriting when adding dynamic fields in Angular 7?

In my current project using Angular, I am tasked with setting up configuration using 4 specific fields: Department Name (select option) Service Name (select option) Status (text input) Level (text input). I need to be able to add multiple sets of these ...

Following modification of a UseState Hook, React component fails to trigger a re-render

After researching various solutions to this issue, I have yet to find a definitive answer. In my code, I utilize a useEffect to fetch an array of objects called "nftRewards". The fetching process works correctly as I can see the data in the console. Howev ...

Guide to encoding an object containing multiple arrays of objects into JSON using PHP

My goal is to generate a JSON structure as shown below: { "success":[{ "success": "1" }], "friends": [ { "name": "ali", "phone": "934453" }, { "name": "reza", "pho ...