JavaScript Program to Merge Property of Two Objects Using Object.assign() Method

Hello friend you may have many doubts about JavaScript Program to Merge Property of Two Objects Using Object.assign() Method We hope this article fills in all the doubts in the article. Let’s get back to the article.

JavaScript Program to Merge Property of Two Objects Using Object.assign() Method

JavaScript Program to Merge Property of Two Objects Using Object.assign() Method

// program to merge property of two objects

// object 1
const person = {
    name: 'Jack',
    age:26
}

// object 2
const student = {
    gender: 'male'
}

// merge two objects
const newObj = Object.assign(person, student);

console.log(newObj);
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog', car: 'chevy'}
var objMerge;

objMerge = JSON.stringify(obj1) + JSON.stringify(obj2);

// {"food": "pizza","car":"ford"}{"animal":"dog","car":"chevy"}

objMerge = objMerge.replace(/}{/, ","); //  _ replace with comma for valid JSON

objMerge = JSON.parse(objMerge); // { food: 'pizza', animal: 'dog', car: 'chevy'}
// Of same keys in both objects, the last object's value is retained_/

Read Also: JavaScript Program to Clone a JS Object Using Spread Operator

Final Words

JavaScript Program to Merge Property of Two Objects Using Object.assign() Method the article will satisfy all your doubts.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment