Reputation: 644
I have two objects:
objectA = {
name: 'myname',
surname: 'mysurname',
age: 'myage'
}
objectB = {
birthdate: 'mybirthdate',
school: 'myschool'
}
How can I add objectA
's age
property to objectB
to get the result below:
objectB = {
birthdate: 'mybirthdate',
school: 'myschool',
age: 'myage'
}
Upvotes: 0
Views: 43
Reputation: 212
Try using either:
objectB.age = objectA.age
or
Object.assign(objectB, { age: objectA.age} );
Upvotes: 1
Reputation: 56770
If you want the object to be a new object (instead of modifying objectB
), you can use object rest spread:
objectA = {
name: 'myname',
surname: 'mysurname',
age: 'myage'
}
objectB = {
birthdate: 'mybirthdate',
school: 'myschool'
}
objectC = { ...objectB, age: objectA.age }
console.log(objectC)
Upvotes: 0
Reputation: 5194
There are various ways :
easiest one :
let obj1 = { food: 'pizza', car: 'ford' }
let obj2 = { animal: 'dog' }
Object.assign(obj1, obj2); //es6
console.log(obj1);
Upvotes: 1