Swap out a collection of objects for a different collection of objects

I need to replace the content of array1 with the content of another array2 while keeping the same references and indexes in array1:

let array1 = [
 {  book : { id : 2, authorId : 3} } ,
 {  book : { id : 3, authorId : 3} },
 {  book : { id : 4, authorId : 3} }
]

 let array2 = [
 {  book : { id : 2, authorId : 3} } ,
 {  book : { id : 3, authorId : 2} },
 {  book : { id : 4, authorId : 2} }
]

I attempted this approach:

[].splice.apply(array1), [0, array1.length].concat(array2));

However, instead of obtaining the content from array2, I still have the original content of array1.

The desired outcome is for array1 to be a copy of array2, like so:

[
     {  book : { id : 2, authorId : 3} } ,
     {  book : { id : 3, authorId : 2} },
     {  book : { id : 4, authorId : 2} }
    ]

Thank you.

Answer №1

To easily duplicate an array, utilize a json copy method:

newArray = JSON.parse(JSON.stringify(existingArray))

Answer №2

Here's an example of how to write it:

newArray = [...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

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

What are the steps to configure Auth0 for an Angular application?

I'm having trouble implementing Auth0 into my angular app. After configuring it on [https://manage.auth0.com/dashboard/], clicking the save changes button results in this error: Error!Payload validation error: 'Object didn't pass validatio ...

What is the best way to iterate through all class properties that are specified using class-validator?

I have a class defined using the class-validator package. class Shape { @IsString() value?: string @IsString() id?: string } I am trying to find a way to retrieve the properties and types specified in this class. Is there a method to do s ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

What benefits does using the --output-hashing=all command bring to an Angular build process?

During production build, a command is used as: ng build --aot --output-hashing=all --prod --base-href "/xyz/" --deploy-url "/xyz/" Can you explain the purpose of --output-hashing=all in this command? ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

Delete the option "x" from the kendo combobox

Is there a way to eliminate or hide the clear ("x") action from a Kendo combobox using TypeScript? I have attempted to find a solution through SCSS/CSS, but I have not been successful. Alternatively, I would be fine with preventing the event triggered by ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

No input in ng2-select2

How can I reset the value in ng2-select2 by clicking on a button? Here is my current HTML code: <select2 id="bill" [data]="colBill" [options]="option" (valueChanged)="onBillArray($event);"> The corresponding Typescript code is: this.arrBill = []; ...

Angular's openLayers functionality makes it easy to add features to a vector source from an XMLHttpRequest

My inspiration came from the use of , where they utilize: vectorSource.addFeatures(vectorSource.getFormat().readFeatures(xhr.responseText)); However, in Angular using TypeScript, addFeatures expects Feature[] while vectorSource.getFormat().readFeatures ...

What is the best way to insert a placeholder React element into a different Component using TypeScript?

I've encountered a Typescript error that has me stumped. Check out the code snippet below: interface AppProps { Component: JSX.ElementClass; pageProps: JSX.ElementAttributesProperty; } const App = ({ Component, pageProps }: AppProps) => { co ...

The error message "The type 'DynamicModule' from Nest.js cannot be assigned to the type 'ForwardReference' within the nest-modules/mailer" was encountered during development

Recently, I decided to enhance my Nest.js application by integrating the MailerModule. I thought of using the helpful guide provided at this link: Acting on this idea, I went ahead and performed the following steps: To start with, I executed the command ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

Update your mappings for the city of Istanbul when utilizing both TypeScript and Babel

Currently, I am facing the challenge of generating code coverage for my TypeScript project using remap Istanbul. The issue arises due to the usage of async/await in my code, which TypeScript cannot transpile into ES5 directly. To circumvent this limitation ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Refreshing manually will display only the JSON data

Utilizing a NodeJS server to fetch information from a MySQL database and presenting it as a JSON object is the task at hand. app.get('/random', (req, res) => { var connection = mysql.createConnection({ host: 'localhost', ...

No invocation of 'invokeMiddleware' was suggested

Encountered this specific issue when setting up loopback4 authentication. constructor ( // ---- INSERT THIS LINE ------ @inject(AuthenticationBindings.AUTH_ACTION) protected authenticateRequest: AuthenticateFn, ) { super(authen ...

Using Angular CLI with ES6 instead of TypeScript for your development needs can offer a

Is there a way to utilize an ES6 transpiler such as Babel instead of TypeScript in an Angular CLI project? Are there any specific flags for specifying the script language, similar to using --style? Thank you. ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

Ways to display an icon with an underline effect upon hovering over text

I have implemented a CSS effect where hovering over text creates an underline that expands and contracts in size. However, I now want to display an icon alongside the text that appears and disappears along with the underline effect. When I try using displa ...