Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy matching properties from one object to another

Tags:

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?

like image 692
sreginogemoh Avatar asked Apr 06 '16 04:04

sreginogemoh


People also ask

How do I copy properties from one object to another in blender?

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.

How can you apply the same properties of an object to other object in Autocad?

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.

How do you copy properties from one object to another in JavaScript?

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.

How do you assign values from one object to another in TypeScript?

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.


1 Answers

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 🌹

like image 174
basarat Avatar answered Oct 21 '22 08:10

basarat