2

I have an array of typed object and I need to create a separated copy of it in order to be able to work on a clone.

I have to pass to configuratorProduct the copy of listProducts value:

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

This is what I'm trying:

  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 problem is that compiler returns:

Property 'idProduct' does not exist on type 'string'

How can i solve it ?

Thanks to support

DarioN1
  • 2,460
  • 7
  • 32
  • 67

4 Answers4

1

You can make a copy using the spread operator

this.configuratorProducts = [...this.listProducts]

bugs
  • 14,631
  • 5
  • 48
  • 52
Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
1

Property 'idProduct' does not exist on type 'string' because there p is string, you made a simple mistake

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

should be

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

for(let p in this.configuratorProducts) is use to iterate keys of object, which are string. of is used to iterate values, which here are Product

And there are two type of cloning: Deep Clone and Shallow Clone, research well before using any.

amitdigga
  • 6,550
  • 4
  • 26
  • 31
1

I like to use this clone function

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;

See a demo here

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

If it is an array it returns an array of each item cloned, if it is a date it creates a new date, if it is an object if reduces the properties onto a new object with each property cloned. If none of these it is a value object or a function and just return it.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

Why don't you use general static clone tool?

For example:

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

@Injectable()
export class ObjectCloneUtility{

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

(I found this in SO, but honestly couldn't find the original answer.)

Or, maybe other clone solutions could work for you as well.

ForestG
  • 17,538
  • 14
  • 52
  • 86