Ahmet Ömer
Ahmet Ömer

Reputation: 644

How to map an Object's property to another object?

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

Answers (3)

moodseller
moodseller

Reputation: 212

Try using either:

objectB.age = objectA.age

or

Object.assign(objectB, { age: objectA.age} );

Upvotes: 1

connexo
connexo

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

programoholic
programoholic

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

Related Questions