Lets say I have an existing object obj1 = {a: 'A', b: 'B', c: 'C', d: 'D'}
I have another object something like obj2 = {b: 'B2', c: 'C2', d: 'D2', e: 'E2'}
Now I want to selectively copy the values of only a few properties from obj2
to obj1
, for rest of the properties in obj1
, I want them unchanged.
Now, say I want to copy of the values of properties b
and d
. I'd want to do something like
obj1 = {a: 'A', b: 'B', c: 'C', d: 'D'};
obj2 = {b: 'B2', c: 'C2', d: 'D2', e: 'E2'};
copyPropertyvalues(
obj2, // source
obj1, // destination
[obj2.b, obj2.d] // properties to copy >> see clarification below
); // should result in obj1 = {a: 'A', b: 'B2', c: 'C', d: 'D2'}
How do I write this method? Note that I also do not want to provide the list of properties as strings, as I'd want compile time safety as much as possible.
So basic asks here are:
- Copy only a few property values from an object
- Copy to an existing object & not create a new one
- Retain other property values in destination object
- Avoid strings for property names (like
'b', 'd'
) and leverageTypeScript
safety as much as possible
Clarification based on comment:
When I say obj2.b
or so in (pseudo) code example
- I do not mean literally
obj2.b
- Rather some way to check at compile time that
b
is actually a property onobj2
's type