Playing with the … spread operator on JSON objects

by | Jan 14, 2018 | IT Tips | 0 comments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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) )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//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.