Posted by Kosal
To merge objects in JavaScript, you can use the spread operator (...)
or Object.assign()
which can be used to merge two or more objects and create a new one that has properties of the merged objects.
If objects have a property with the same name, then the right-most object property overwrites the previous one
(...)
const obj = {...obj1, ...obj2, ...}
const user = {
firstName: "Kosal",
lastName: "Ang",
age: 30,
country: "USA",
};
const profile = {
jobTitle: "Programmer",
country: "Cambodia",
city: "Phnom Penh",
};
const employee = {
...user,
...profile,
};
console.log(employee);
{
"firstName": "Kosal",
"lastName": "Ang",
"age": 30,
"country": "Cambodia",
"jobTitle": "Programmer",
"city": "Phnom Penh"
}
Object.assign(target, sourceObj1, sourceObj2, ...);
const user = {
firstName: "Kosal",
lastName: "Ang",
age: 30,
country: "USA",
};
const profile = {
jobTitle: "Programmer",
country: "Cambodia",
city: "Phnom Penh",
};
const employee = Object.assign(user, profile);
console.log(employee);
{
"firstName": "Kosal",
"lastName": "Ang",
"age": 30,
"country": "Cambodia",
"jobTitle": "Programmer",
"city": "Phnom Penh"
}