Replicating an array of typed objects in Angular2

I have a collection of specific object types and I'm looking to duplicate it so that I can work on a separate version.

In order for the configuratorProduct to function correctly, I need to provide it with a copy of the listProducts values:

  listProducts: Product[];
  configuratorProducts : Product[];

This is my current approach:

  this.configuratorProducts = this.listProducts.map(x => Object.assign({}, x));
    for(let p in this.configuratorProducts)
    {
      var ck = this.accessories.filter(x=> x.idProductParent == p.idProduct);
    }

The issue I am encountering is that the compiler is displaying:'Property 'idProduct' does not exist on type 'string'

How can this be resolved?

Thanks for your assistance.

Answer №1

This clone function is quite handy for me

const clone = obj =>
  Array.isArray(obj)
    ? obj.map(item => clone(item))
    : obj instanceof Date
      ? new Date(obj.getTime())
      : (typeof obj === 'object') && obj
        ? Object.getOwnPropertyNames(obj).reduce((o, prop) => ({ ...o, [prop]: clone(obj[prop]) }), {})
        : obj;

Take a look at the live demo

https://stackblitz.com/edit/typescript-qmzgf7

If the input is an array, it returns a cloned array with each item. If it's a date, a new date object is created. If it's an object, the properties are reduced to a new object with each property cloned. Otherwise, it just returns the value or function as is.

Answer №2

To duplicate an array, utilize the spread operator

newProducts = [...originalArray]

Answer №3

Property 'idProduct' does not exist on type 'string'
because the variable p is of type string. A simple mistake was made.

for(let p in this.configuratorProducts)
{
  ...
}

This should be corrected to:

for(let p of this.configuratorProducts)
    {
      ...
    }

for(let p in this.configuratorProducts)
is used to iterate over keys of an object, which are strings. The of keyword is used to iterate over values, which in this case are Product.

It's important to understand the difference between Deep Clone and Shallow Clone before using either method.

Answer №4

Have you considered using a generic static clone tool?

Take this code snippet for instance:

import {Injectable} from "@angular/core";

@Injectable()
export class ObjectCopier{

  public static duplicate(obj: Object): Object {
    if (null == obj || "object" != typeof obj) return obj;
    let copy = obj.constructor();
    for (let prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        copy[prop] = obj[prop];
      }
    }
    return copy;
  }
}

(I came across this on SO, but couldn't locate the original source.)

Alternatively, you may find success with other methods of object cloning as well.

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

Circular dependency in Angular between two components

I'm currently working on an Angular 7 project that involves managing different entities, like Cars and Students. The structure of the application components can be represented by the following hierarchy: Cars Cars/CreateCar (dialog) Students Studen ...

Ensure the variable is valid by using a type guard in the false branch

I am attempting to use a type guard to narrow down a complex type. In my scenario, I want the false branch of the type guard to recognize the complement of the narrowed type. interface Model { side: 'left' | 'right'; } interface LeftMo ...

A guide on verifying input for null with ngIf

I need to verify if the Comment is not null in order to display the div Error: Template parse issue - Unexpected closing tag "div". This error can occur if the tag has already been closed by another tag. For more information, please refer to: &l ...

Avoiding redundant requests with the same parameters in Angular/NGRX

Imagine having a component designed to showcase a list of actors from a movie. When this component loads, it triggers an action to retrieve the actors' data. actors.component.ts @Input() filter; // for example, only displaying male actors ngOnInit( ...

Displaying updated information in Angular

I recently developed a chat application using Angular that utilizes the stomp socket from @stomp/ng2-stompjs. To display all messages, I am leveraging *ngFor. <p *ngFor="let item of messages" style="padding: 5px; font-size: 18px"> <span style ...

Modify the data displayed on the chart by choosing the desired year from the dropdown options

In my Angular app, I am showcasing a chart that visualizes data based on selected starting and ending years from dropdown menus. The X axis represents 18 cities, while the Y axis displays "IAP" values. To calculate the "IAP" values for each city within the ...

The method Observable.combineLatest is not implemented

One of the features on my website is the Home page, where users can click on Contact me to navigate to the Contact page: home.component.html <div> <a routerLink="/contact" [queryParams]="sendOBj">Contact me</a> </div> home.comp ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. https://i.sstatic.net/jQ62l.png .html <ion-slides [pager]="true" [slide ...

How to generate a SHA256 hash of the body and encode it in base64 using Python compared to

I'm aiming to hash the body using SHA256 and then encode it with base64. I'm in the process of converting my code from Python to TypeScript. From what I gathered via a Google search, it seems like crypto can be utilized instead of hashlib and ba ...

Troubleshooting: Why is my switch-case statement in TypeScript not functioning as expected

Here is a simple switch case scenario: let ca: string = "2"; switch (ca) { case "2": console.log("2"); case "1": console.log("1"); default: console.log("default"); } I am puzzled by the output of this code, which is as follows: 2 1 defa ...

Error in Ionic2 TypeScript: 'google' and '$' names not found, despite Google Maps and jQuery functioning correctly

I am currently working on developing an ionic2 application using TypeScript. Within the index.html file, I have attempted to integrate jquery and the Google Maps JS API before cordova.js: <!-- Vendor --> <script src="https://maps.googleapis. ...

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

The passing of values from a parent component to a child component seems to be encountering issues in the

I'm attempting to send json values using the Input decorator, but I am encountering issues. I have tried passing data from a parent component to a child component, but it is not functioning correctly. Child Component <div class="card"> <d ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error: The component FoodComponent is not part of a ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

Transferring data between ngModel instances

item-inventory.component.html <div *ngIf="selectedItem"> <h2>Product Information</h2> <div>ID: {{ selectedItem.id }}</div> <div> Name: <input type="text" ngM ...

My project in WebStorm encounters a setback due to the updated release of Typescript 5+

Recently, I had to upgrade my TypeScript version from 4.9.5 to 5.1.3 because one of the libraries I'm using made a fix that required a newer TypeScript version. After the update, TypeScript started throwing errors for console calls and React event di ...