Playing with the … spread operator on JSON objects

Written by James McDonald

January 14, 2018


const stringify = (obj) => {
        // use 2 spaces and pretty print it
	return JSON.stringify(obj, null, 2)
}

const token = "hijames"

// starting array
const config = {
  headers: {
    'Authorization': `Bearer ${token}`,
    "Content-Type": "text/plain",
    "Accept": "application/json"
  }

}

// array to merge with the above
const myInit = {
  method: 'POST',
  mode: 'cors',
  cache: 'default'
};

const config1 = {
  ...config,
  myInit
}

console.log("...spread Operator\n", stringify(config1))

const config3 = { ...config, ...myInit }

console.log("...spread Operator used on both objects\n", stringify(config3))

const config2 = Object.assign(config, myInit)

console.log("Using Object.assign\n", stringify(config2) )

//output of the above
// if you don't use the spread operator
// on the second object it will include
// the object variable name
...spread Operator
 {
  "headers": {
    "Authorization": "Bearer hijames",
    "Content-Type": "text/plain",
    "Accept": "application/json"
  },
  "myInit": {
    "method": "POST",
    "mode": "cors",
    "cache": "default"
  }
}

// this works as expected
...spread Operator used on both objects
 {
  "headers": {
    "Authorization": "Bearer hijames",
    "Content-Type": "text/plain",
    "Accept": "application/json"
  },
  "method": "POST",
  "mode": "cors",
  "cache": "default"
}

// another way
Using Object.assign
 {
  "headers": {
    "Authorization": "Bearer hijames",
    "Content-Type": "text/plain",
    "Accept": "application/json"
  },
  "method": "POST",
  "mode": "cors",
  "cache": "default"
}

0 Comments

Submit a Comment

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…