ES6 Deep copy with Object Spread Properties

JS
S
JavaScript

Simple example, by creating a deep copy of a javascript android app from a web app.

1const web_app = {
2  url: "www.coderecipes.org",
3  type: 'web',
4  msg_brokers: [
5    "rabbitmq"
6  ]
7};
8
9// Shallow Copy via Object Spread Properties
10const android_app = {
11    ...web_app,
12    msg_brokers: [
13        'activemq'
14    ]
15};
16
17android_app.type = 'android';
18android_app.msg_brokers.push('advancedmq');
19
20console.log(JSON.stringify(android_app, null, 2));
21console.log("------------");
22console.log(JSON.stringify(web_app, null, 2));
23
24// Alternatives
25Object.assign({}, obj)
26JSON.parse(JSON.stringify(obj))
27
28// Recommended
29https://www.npmjs.com/package/clone
30

Created on 6/14/2017