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

2
  • what is the type of Product .? Commented Apr 18, 2018 at 12:24
  • Its a simple class Commented Apr 18, 2018 at 12:24

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can make a copy using the spread operator

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

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.