In this post we will merge objects in JavaScript
const user = {
user_id: '1#inoque@20',
first_name: 'Francisco',
last_name: 'Inoque',
age: 24
}
const user_details = {
obj_id: '1122@ee11',
user_id: '1#inoque@20',
company: 'SavanaPoint',
role: 'Full Stack Developer',
hobby: 'Watching Movies',
stacks: {
languages: ['JavaScript', 'Rust', 'Go'],
frameworks: {
frontend: ['Angular', 'Reactjs', 'Nextjs', 'Bootstrap'],
backend: ['Nestjs', 'Express', 'Adonisjs', 'Nodejs'],
database: ['MongoDB', 'FaunaDB'],
other_tech: ['firebase', 'graphql', 'TypeScript', 'Adobe XD', 'Nodejs']
}
}
}
const user_complete_details = {
...user, ...user_details
}
Or we can use: Object.assign
The Object.assign () method is used to copy the values of all the own enumerable properties of one or more source objects to a target object. This method will return the target object.
const user = {
user_id: '1#inoque@20',
first_name: 'Francisco',
last_name: 'Inoque',
age: 24
}
const user_details = {
obj_id: '1122@ee11',
user_id: '1#inoque@20',
company: 'SavanaPoint',
role: 'Full Stack Developer',
hobby: 'Watching Movies',
stacks: {
languages: ['JavaScript', 'Rust', 'Go'],
frameworks: {
frontend: ['Angular', 'Reactjs', 'Nextjs', 'Bootstrap'],
backend: ['Nestjs', 'Express', 'Adonisjs', 'Nodejs'],
database: ['MongoDB', 'FaunaDB'],
other_tech: ['firebase', 'graphql', 'TypeScript', 'Adobe XD', 'Nodejs']
}
}
}
const user_complete_details = Object.assign(user, user_details)
console.log(user_complete_details)
Result:
{
user_id: '1#inoque@20',
first_name: 'Francisco',
last_name: 'Inoque',
age: 24,
obj_id: '1122@ee11',
company: 'SavanaPoint',
role: 'Full Stack Developer',
hobby: 'Watching Movies',
stacks: {
languages: [ 'JavaScript', 'Rust', 'Go' ],
frameworks: {
frontend: [Array],
backend: [Array],
database: [Array],
other_tech: [Array]
}
}
}
Or
{user_id: "1#inoque@20", first_name: "Francisco", last_name: "Inoque", age: 24, obj_id: "1122@ee11", …}
age: 24
company: "SavanaPoint"
first_name: "Francisco"
hobby: "Watching Movies"
last_name: "Inoque"
obj_id: "1122@ee11"
role: "Full Stack Developer"
stacks:
frameworks:
backend: Array(4)
0: "Nestjs"
1: "Express"
2: "Adonisjs"
3: "Nodejs"
length: 4
__proto__: Array(0)
database: Array(2)
0: "MongoDB"
1: "FaunaDB"
length: 2
__proto__: Array(0)
frontend: Array(4)
0: "Angular"
1: "Reactjs"
2: "Nextjs"
3: "Bootstrap"
length: 4
__proto__: Array(0)
other_tech: (5) ["firebase", "graphql", "TypeScript", "Adobe XD", "Nodejs"]
__proto__: Object
languages: Array(3)
0: "JavaScript"
1: "Rust"
2: "Go"
length: 3
__proto__: Array(0)
__proto__: Object
user_id: "1#inoque@20"
__proto__: Object
Top comments (8)
Thanks to everyone for the tips. So you make me strong
Some comments may only be visible to logged-in visitors. Sign in to view all comments.