Create duplicates of both the array and its individual elements by value

I'm having trouble figuring out how to properly copy an array along with all its elements.

In my model, I have a name and options, both of which are strings.

This is what I currently have:

const myArrayToDuplicate = [myModel, myModel, myModel]

My attempt to duplicate the array is like this:

const duplicate = Object.assign([], myArrayToDuplicate);
console.log(duplicate === myArrayToDuplicate) //false
console.log(duplicate[0] === myArrayToDuplicate[0]) //true -> not desired

Then I tried:

duplicate[0] = Object.assign(myArrayToDuplicate[0]) 
//still true

Could someone advise me on the correct way to achieve this task?

Answer №1

For the best results, I recommend utilizing a deep copy function, like the one offered by lodash:

import * as _ from "lodash";
let copiedArray = _.cloneDeep(myArrayToDuplicate);

This method is particularly useful because it can handle copying arrays of any depth.

Answer №2

One potential resolution may involve

const copiedArray = originalArray.map(item => ({...item}))

copiedArray === originalArray // false
copiedArray[0] === originalArray[0] // false

Answer №3

const copiedArray = originalArray.map((element) => Object.assign({}, element));

As stated on the official documentation, the Object.assign method copies all properties from the second argument into the first one.

It's worth noting that, as highlighted by Learning a Mess, this approach may not work effectively with complex objects like nested objects.

Answer №4

Here are several options to consider

const myArrayToClone = [myModel, myModel, myModel];
const sameMemoryRef = myArrayToClone; // Same memory reference
const newMemoryRef = [...myArrayToClone]; // Different memory reference, but objects remain the same
const  totalMemoryDiff = [...myArrayToClone.map(obj => ({...obj}))]; // Complete memory difference

To summarize:

  • If you change sameMemoryRef, your original array will also be affected.
  • If you modify newMemoryRef, the original array remains unchanged
    • Changing the objects within it will reflect in the original array
  • Modifying anything in totalMemoryDiff will not impact the original array.

Answer №5

To perform a deep copy of an object, you can utilize JSON.parse and JSON.stringify methods.

let originalObj = { name: "John", age: 30 };
let copiedObj = JSON.parse(JSON.stringify(originalObj));

Answer №6

To create a deep copy, the following method can be used:

const copiedArray = JSON.parse(JSON.stringify(originalArray))

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

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

Utilize prop-types inheritance when a component is rendered via props

Is it possible to inherit prop-types when a component is rendered via the parents prop, without direct access to 'ChildProps' and 'Props' interface? Parent Component interface ChildProps { counter: number; setCounter: React.Dispat ...

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

A guide on implementing code sharing in NestJS using Yarn Workspaces

I'm currently working on a proof of concept for a basic monorepo application. To structure my packages, I've decided to use Yarn Workspaces instead of Lerna as it seems more suitable for my needs. One of the packages in my setup is shared, which ...

Provide the context for a template within a dynamically generated component

I have been working on creating a component similar to a tooltip control, but I am facing an issue. The current setup only supports simple text in the ng-template, and when attempting to pass a more complex template with bindings, it breaks. To address thi ...

Remove the JavaScript files from the distribution folder when removing TypeScript files in an Angular 2 project

I came across a solution that recommended separating Angular2 TypeScript files and JavaScript files into different folders like 'dist'. By following this, I moved my files to the 'app' and 'dist' folders. Interestingly, whenev ...

Angular2 Error: ngClass used in a Host component, "is not recognized as a valid native property"

Is it feasible to utilize the "ngClass" directive within the host for a component or directive? @Component({ selector: 'custom', template: `<div [ngClass]="classMap"></div> // It works <ng-content></ng-content&g ...

Using lambdas in JSX attributes is not allowed because it can negatively impact rendering performance

I encountered an error when using the following code:- <FieldArray name="amenities" render={arrayHelpers => ( <div> {values.amenitieslist && values.amenitieslist.length > 0 ? ( val ...

Issue encountered on server using next.js - FetchError: failed to process request for https://jsonkeeper.com/b/4G1G

Struggling to fetch JSON data from a link and destructure it for use on the website. I have a getStaticProps export function that extracts the data and I want to pass it into my default Home function to iterate through it. I have come across information ab ...

User's information will only be updated once the page is refreshed

I am encountering an issue with displaying two ul elements based on user login status. When I log in, the first ul is shown immediately, but the second ul is only displayed after a page refresh. Initially, the value in "accountService.currentUser" is null ...

How can TypeScript be forced to output a specific data type?

I've created a generic "fetcher" function that is designed to handle different types of entities. However, I'm encountering an issue where TypeScript is inferring the return type based on all possible conditions within the function. Is there a w ...

Using Firebase's REST API to send a PATCH request

Greetings, I am currently working on an Angular application that utilizes Firebase. I need to update a record in my database and I am using the REST API for this purpose: this.http.patch(fireBaseConfigDBEndpointCloudReference + this.logIn.getUser().valu ...

Encountered error when attempting to clone Angular project using npm: ELIFECY

Hi there, I'm facing an issue with cloning my Angular project. Whenever I try to run the frontend using IntelliJ or VSCode, I'm encountering this error message: C:\Users\developer.me\Downloads\TestClone\node_modules&bsol ...

Angular 4: Implementing toggle switch functionality in Angular 4 by binding boolean values retrieved from the database

Within my application, I am facing an issue with binding a toggle switch to data stored in the database. The data in the database is represented by a field called Status, which can have values of True or False. My goal is to incorporate toggle switch butto ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

Methods for hiding and showing elements within an ngFor iteration?

I am working on an ngFor loop to display content in a single line, with the option to expand the card when clicked. The goal is to only show the first three items initially and hide the rest until the "show more" button is clicked. let fruits = [apple, o ...

What is the best way to generate inner HTML components within Angular by creating components?

I want to create a custom component that functions similarly to Material Tabs. I currently can use Material Tabs to create tabs like this <mat-tab-group mat-align-tabs="center"> <mat-tab label="First Tab"> <p& ...

Declarations for TypeScript in NPM packages

In order to streamline my development process with bun.sh using workspaces as npm packages, I have created a tool available here. However, I am facing two issues: After bun installing the 'core' packages from npm and testing a sample, I encounte ...

Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc. The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening? To investigate the issue, I tested my ...

"Error: Unfinished string literal encountered" occurring in a TypeScript app.component.ts file in NativeScript

I've been trying to learn NativeScript through a tutorial, but I keep encountering errors. Here is an excerpt from my app.component.ts file: import { Component } from '@angular/core'; @Component ({ selector: 'my-app', temp ...