Merge Multiple Objects in JavaScript

Did you ever try to merge multiple objects into one single object in JavaScript? You may wonder how to create one object that will hold all the items of our objects.

Well, this article is going to show you how to combine two or more JavaScript objects and get a single object. This task is very useful in creating classes with options. It is very popular in JavaScript libraries to merge objects. It let users set options.

First of all, let’s see our three objects below:

var fruit = { name: 'Mango', test: 'Good' };
var property = { color: 'Yellow', test: 'Sweet', size: 'big' };
var price = { market: '40', wholesale: '25' };

Now, we want to merge these three objects. So let’s continue reading to learn how can we do this specific task…

Well, you will be amazed to know that we can do it easily just by using three dots before each object variable.

Well, I am not kidding. You will soon understand what I am going to do.

JavaScript code to Merge Multiple Objects

See the code below:

var fruit = { name: 'Mango', test: 'Good' };
var property = { color: 'Yellow', test: 'Sweet', size: 'big' };
var price = { market: '40', wholesale: '25' };

var shortInfo = {...fruit, ...property, ...price};
console.log(shortInfo);

The above code will give the output in the console that you can see below:

Object {
      color: "Yellow"
      market: "40"
      name: "Mango"
      size: "big"
      test: "Sweet"
      wholesale: "25"
}

You can clearly see that the output contains all the value or items from our three objects. That means we are able to merge the three objects into a single one just by using three dots before each object variable. The power of three dots is amazing. It is able to let us do the task easily.

Also, read:

Here in our example, we have combined only three objects. Well, we can do the same thing with two or even more than three objects.

 

Leave a Reply

Your email address will not be published. Required fields are marked *