Angular2 - 类型化对象的克隆数组

标签 angular typescript

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

我必须将 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”不存在于 输入“字符串”

如何解决?

感谢支持

最佳答案

我喜欢使用这个克隆功能

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

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

关于Angular2 - 类型化对象的克隆数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899612/

相关文章:

javascript - 将 JavaScript 函数重写为类方法? ( typescript 可能)

angular - 未定义未捕获的引用输入 - @Input() 在 Angular 2 中不起作用

typescript - 扩展另一个类的类的 TS 类型是什么?

javascript - Subject.subscribe 在构造函数之外不工作

angular - 使用 Angular CDK DRAG 丢失拖动元素上的旋转位置

angular - 错误 : Cannot find module '@angular/compiler-cli

typescript - TS2345 即使在不可能的路径上

javascript - 如何在 TypeScript 中声明数组对象

angular - 在这个例子中为什么模板变量的值是 "ngModel"

javascript - 在 Angular Material mat-select 之上创建自定义组件