Reputation: 2552
I have two object classes that are very similar and I need to know if there is a way to easily assign all the common property values from object1 to object2.
This is the scenario:
let obj1:Product;
left obj2:OffertRow;
The common properties for instances are: idProduct, ProductName
Is there a way to do something like this in order to pass obj2 properties on obj1 one:
obj1 = obj2
Or I always have to specify the properties:
obj1.idProduct = obj2.idProduct;
obj1.Product = obj2.Product;
.... = ...
Thanks to support
Upvotes: 2
Views: 1185
Reputation: 15313
An option is to create an array of the common properties and iterate over it.
let commonProps = ['idProduct', 'ProductName'];
commonProps.map(x => {
obj1[x] = obj2[x] // or use the spread operator {...obj2[x]} if you need to be more carefull
})
Alternative solution using Object.keys
:
Object.keys(obj2)
.filter(x => Object.keys(obj1).includes(x))
.map(x => obj1[x] = obj2[x])
Upvotes: 0
Reputation: 131396
You could use 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]
}
})
})
Upvotes: 1
Reputation: 701
Object.assign(obj1, obj2) ist what you are looking for.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
EDIT: sorry i thought you we're talking about JSON objects not classes. Wrong answer!
Upvotes: 0