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?
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?
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 don't mind any keys of obj2
not exist in obj1
, a clearer way is using Object.assign(obj1, obj2)
:
I think @basarat meant to iterate over the target properties not the source ones like this
function CopyMatchingKeyValues(Target, Source) {
return Object.keys(Target).forEach(key => {
if (Source[key] !== undefined)
Target[key] = Source[key];
});
}
Actually he is testing for key matching it won't matter.