I have these two objects:
obj1 = {a: '', b: ''}
obj2 = {a: '1', b: '2', c: '3'}
I want to copy all matching properties from obj2
to obj1
. What is the best way of doing that in Typescript?
Object Mode. Select more than one object, press Ctrl - C to copy attributes from active to selected, you'll see the following menu: Each item on the menu will copy some attributes from the active (last selected object) to all the other selected items: Copy Location.
You can open the 'Match Properties' command by clicking on the icon (below left) on your toolbar, or by typing in 'matchprop' in the command line at the bottom of your screen. Once the command has been activated, you will be prompted to select the source object, i.e. the object whose properties you would like to copy.
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
what is the best way of doing that in typescript
Same as in JavaScript. Just use Object.keys
The following code moves stuff from obj2 to obj1:
let obj1 = {a: '', b: ''}
let obj2 = {a: '1', b: '2', c: '3'}
Object.keys(obj2).forEach(key=>obj1[key]=obj2[key]);
For any condition like must not already be in obj1 etc you can do that check in the forEach
🌹
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With