Angular/Typescript - 在两个相似对象之间分配对象属性的快速方法

标签 angular typescript

我有两个非常相似的对象类,我需要知道是否有一种方法可以轻松地将所有公共(public)属性值从对象 1 分配给对象 2。

这是场景:

let obj1:Product;
left obj2:OffertRow;

实例的通用属性是:idProduct, ProductName

有没有办法做这样的事情,以便在 obj1 上传递 obj2 属性:

obj1 = obj2

或者我总是必须指定属性:

obj1.idProduct = obj2.idProduct;
obj1.Product = obj2.Product;
.... = ...

感谢支持

最佳答案

你可以使用 Object.keys()

The Object.keys() method returns an array of a given object's properties names, in the same order as we get with a normal loop.

var obj1 = {}
var obj2 = {}
Object.keys(obj2).forEach(key2 => {
  Object.keys(obj1).forEach(key1 => {
    if (key1 === key2) {
      obj1[key1] = obj2[key1]
    }
  })
})

关于Angular/Typescript - 在两个相似对象之间分配对象属性的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132052/

相关文章:

javascript - Angular 2 应用程序中的 Service Worker 实现

Angular/Typescript Eval 和这个

接口(interface)的 TypeScript 反射

typescript - "Type ' () => string[] ' is missing the following properties from type ' string[] ': pop, push, concat, join, and 25 more" typescript 中出现错误

javascript - 如何将一个对象的现有属性以 Angular 复制到另一个对象?

angular - 使用类装饰器时需要未捕获的反射元数据垫片

javascript - Angular : No Error but not showing data in Material Table

angular - 填充数组并使用 Angular Material 使其可过滤

javascript - pdfmake - 在 ANGULAR 4 中将 SVG 转换为 image64

angular - 使用 forkjoin 合并 http observables