EN
JavaScript - merge two objects properties dynamically
3 points
In this article, we would like to show you how to merge two object properties dynamically in JavaScript.
Quick solution:
xxxxxxxxxx
1
const result = {
2
object1,
3
object2
4
}
Hint: be careful, presented solutions in this example merged object only on the first level (
object1
andobject2
direct properties will be combined - without child object properties).To make full merge it is necessary to iterete grought all objects, or use some library.
In this example, we merge object1
and object2
into the result
object.
Spread operator (...
) was introduced in ES6.
xxxxxxxxxx
1
const object1 = {
2
1: 'a',
3
2: 'b'
4
}
5
const object2 = {
6
2: 'c',
7
3: 'd'
8
}
9
10
const result = {
11
object1,
12
object2
13
}
14
15
console.log(JSON.stringify(result, null, 2));
Output:
xxxxxxxxxx
1
{
2
"1": "a",
3
"2": "c",
4
"3": "d"
5
}
Note:
If the property from
object2
is the same as property fromobject1
, it will be overwritten.
Object.assign()
was introduced in ES6.
xxxxxxxxxx
1
const object1 = {
2
1: 'a',
3
2: 'b'
4
}
5
const object2 = {
6
2: 'c',
7
3: 'd'
8
}
9
10
const result = Object.assign({}, object1, object2);
11
12
console.log(JSON.stringify(result, null, 2));
Note:
If the property from
object2
is the same as property fromobject1
, it will be overwritten.