JavaScript Spread Operator: Object

featured image

The JavaScript Spread operator is a power JavaScript operator to merge JavaScript objects. It can be used to merge objects and it can also be used to merge arrays.

Before ES6 was rolled out, for you to merge objects, you might need to used different methods to achieve one simple result, but with JavaScript Spread operator, all you need to do is to create a new variable and spread all the data of the objects you want to merge.

Example on how to use JavaScript Spread operator to merge Objects

I have two objects containing names of basicInfo and “education but i want to merge them together as one.

      const basicInfo = {
        name: 'John',
        age: 24,
        height: '152cm',
      };
      console.log(basicInfo);

      const education = {
        basis: '2000 - 2005',
        high_School: '2006 - 2011',
        first_Degree: '2012 - 2016',
      };
      console.log(education);

      const bio = { ...basicInfo, ...education };
      console.log(bio);

Result

JavaScript Spread operator

A very cool feature of spread operator is that, you can also add data while spreading the old data in the new object

Example

const basicInfo = {
        name: 'John',
        age: 24,
        height: '152cm',
      };
      console.log(basicInfo);

      const education = {
        basic: '2000 - 2005',
        high_School: '2006 - 2011',
        first_Degree: '2012 - 2016',
      };
      console.log(education);

      const bio = {  ...basicInfo, country: 'England', ...education };
      console.log(bio);

Result

JavaScript Spread operator

Not only in between the objects, you can add data at the beginning or even at the end

Example

      const education = {
        basic: '2000 - 2005',
        high_School: '2006 - 2011',
        first_Degree: '2012 - 2016',
      };
      console.log(education);

      const bio = {
        job: 'Analyst',
        ...basicInfo,
        country: 'England',
        ...education,
        language: 'English',
      };
      console.log(bio);

Result

JavaScript Spread operator

This tutorial aims at giving you a general idea about the JavaScript spread operator, it’s symbol and how it works. we have used object as example in this tutorial, you can learn how to use it to merge arrays in JavaScript using this operator here There are also other JavaScript array methods, like the one you can use to add or delete item from an array, you can find some here

There are more you can do with the spread operator but hopefully this tutorial gives you a good understanding.

1 thought on “JavaScript Spread Operator: Object”

  1. Pingback: JavaScript Spread Operator: Array - codeharis

Leave a Comment

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