【问题标题】:Angular2 - Clone array of typed ObjectAngular2 - 类型化对象的克隆数组
【发布时间】:2018-09-28 16:33:49
【问题描述】:

我有一个类型化对象数组,我需要为其创建一个单独的副本,以便能够在克隆上工作。

我必须将 listProducts 值的副本传递给 configuratorProduct:

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

这就是我正在尝试的:

  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);
    }

问题是编译器返回:

属性“idProduct”不存在于 输入“字符串”

我该如何解决?

感谢支持

【问题讨论】:

  • 产品的类型是什么?
  • 这是一个简单的类

标签: angular typescript


【解决方案1】:

为什么不用通用的静态克隆工具呢?

例如:

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;
  }
}

(我在 SO 中找到了这个,但老实说找不到原始答案。)

或者,也许其他clone solutions 也可以为您工作。

【讨论】:

    【解决方案2】:

    您可以使用扩展运算符制作副本

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

    【讨论】:

      【解决方案3】:

      Property 'idProduct' does not exist on type 'string' 因为pstring,你犯了一个简单的错误

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

      应该是

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

      for(let p in this.configuratorProducts) 用于迭代对象的键,它们是字符串。 of用于迭代值,这里是Product

      而且克隆有两种类型:深克隆和浅克隆,使用前请先研究。

      【讨论】:

        【解决方案4】:

        我喜欢用这个克隆功能

        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;
        

        在这里查看演示

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

        如果它是一个数组,它返回一个包含每个克隆项目的数组,如果它是一个日期,它创建一个新日期,如果它是一个对象,如果将属性减少到一个新对象上,每个属性都被克隆。如果这些都不是值对象或函数,则返回它。

        【讨论】:

          猜你喜欢
          • 2019-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-06
          • 2012-05-06
          • 2015-06-01
          • 2021-01-07
          • 2018-05-26
          相关资源
          最近更新 更多