In Vue, you can Object.assign()
combine three objects into one using methods or the Spread Operator. Here are examples of both methods:
-
How to use
Object.assign()
:const obj1 = { key1: 'value1' }; const obj2 = { key2: 'value2' }; const obj3 = { key3: 'value3' }; const mergedObj = Object.assign({}, obj1, obj2, obj3);
In the example above, we created three objects
obj1
,obj2
andobj3
. They are thenObject.assign()
combined into a new empty object using the method and the result is stored inmergedObj
. -
Use the spread operator (Spread Operator):
const obj1 = { key1: 'value1' }; const obj2 = { key2: 'value2' }; const obj3 = { key3: 'value3' }; const mergedObj = { ...obj1, ...obj2, ...obj3 };
In the above example, we use the spread operator (
...
) to expand the properties of the three objects, then use curly braces{}
to create a new object, put the expanded properties into it, and store the result inmergedObj
.
Whichever method you choose, the properties of the three objects will be merged into a new object that mergedObj
will contain the properties of all three objects. If there are duplicate property names, the properties of the later objects will override the properties of the earlier objects.