How to copy a Map into another Map? [duplicate] - javascript

This question already has answers here:
Shallow-clone a Map or Set
(6 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 2 years ago.
How do I clone/copy a Map in JavaScript?
I know how to clone an array, but how do I clone/copy a Map?
var myArray = new Array(1, 2, 3);
var copy = myArray.slice();
// now I can change myArray[0] = 5; & it wont affect copy array
// Can I just do the same for map?
var myMap = new ?? // in javascript is it called a map?
var myMap = {"1": 1, "2", 2};
var copy = myMap.slice();

With the introduction of Maps in JavaScript it's quite simple considering the constructor accepts an iterable:
var newMap = new Map(existingMap)
Documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

A simple way (to do a shallow copy) is to copy each property of the source map to the target map:
var newMap = {};
for (var i in myMap)
newMap[i] = myMap[i];
NOTE: newMap[i] could very well be a reference to the same object as myMap[i]

Very simple to just use Object.assign()
let map = {'a': 1, 'b': 2}
let copy = Object.assign({}, map);
// Or
const copy = Object.assign({}, {'a': 1, 'b': 2});

JQuery has a method to extend an object (merging two objects), but this method can also be used to clone an object by providing an empty object.
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
More information can be found in the jQuery documentation.

If you need to make a deep copy of a Map you can use the following:
new Map(JSON.parse(JSON.stringify(Array.from(source))));
Where source is the original Map object.
Note this may not be suitable for all use cases where the Map values are not serializable, for more details see: https://stackoverflow.com/a/122704/10583071

There is nothing built in.
Either use a well tested recursive property copier or if performance isn't an issue, serialise to JSON and parse again to a new object.

There is no built-in (edit: DEEP) clone/copy. You can write your own method to either shallow or deep copy:
function shallowCopy(obj) {
var result = {};
for (var i in obj) {
result[i] = obj[i];
}
return result;
}
function deepCopy(obj) {
var result = {};
for (var i in obj) {
// recursion here, though you'll need some non-trivial logic
// to avoid getting into an endless loop.
}
return result;
}
[EDIT] Shallow copy is built-in, using Object.assign:
let result = Object.assign({}, obj);
All objects in Javascript are dynamic, and can be assigned new properties. A "map" as you refer to it is actually just an empty object. An Array is also an object, with methods such as slice and properties like length.

I noticed that Map should require special treatment, thus with all suggestions in this thread, code will be:
function deepClone( obj ) {
if( !obj || true == obj ) //this also handles boolean as true and false
return obj;
var objType = typeof( obj );
if( "number" == objType || "string" == objType ) // add your immutables here
return obj;
var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
if( obj instanceof Map )
for( var key of obj.keys() )
result.set( key, deepClone( obj.get( key ) ) );
for( var key in obj )
if( obj.hasOwnProperty( key ) )
result[key] = deepClone( obj[ key ] );
return result;
}

Related

Object.create copying reference of array and object properties [duplicate]

This question already has answers here:
Crockford's Prototypal inheritance - Issues with nested objects
(3 answers)
Closed 7 years ago.
I am trying to understand how Object.create copies arrays and objects properties when initiating a new object. It seems to be different then copying a string or number. For example if we have a basic Object with a number and array property. jsfiddle example
var obj = {
num: 0, arr: []
};
We then initiate 3 new Objects from this base.
var set1 = Object.create(obj);
set1.num = 10;
set1.arr.push(1);
var set2 = Object.create(obj);
var set3 = Object.create(obj, {arr: []});
I was expecting set2.num and set2.arr property to be it's initial state. I found this to be true for the number, but not the array. Of course one work around is to pass {arr: []} when initiating the Object or creating a initiation function that resets the arr property.
// false
console.log(set1.num === set2.num);
// true - why is this true???
console.log(set1.arr === set2.arr);
// false
console.log(set1.arr === set3.arr);
Is this the normal behavior? Is Object.create keeping a reference to all of the Object's array and object properties? It would be very nice to not have to create new arrays and objects when initiating a new Object.
It would be very nice to not have to create new arrays and objects when initiating a new Object
Write a function in your favourite style
Returning a literal
function makeMyObject() {
return {num: 0, arr: []};
}
// usage
var obj = MyObject();
Returning an Object.created object, and assigning to it,
function makeMyObject() {
var o = Object.create(null); // or some prototype instead of `null`
return Object.assign(o, {num: 0, arr: []});
}
// usage
var obj = MyObject();
Using new
function MyObject() {
this.num = 0;
this.arr = [];
}
// usage
var obj = new MyObject();
Cloning is a bit more complicated, a basic example might be
function shallowClone(o) {
var e;
if (typeof o !== 'object')
return o;
e = Object.create(Object.getPrototypeOf(o));
// copy enumerable references
Object.assign(e, o);
// or to keep non-enumerable properties
// Object.defineProperties(b, Object.getOwnPropertyNames(o).map(Object.getOwnPropertyDescriptor.bind(Object, o)));
return e;
}
Deep cloning requires looping over properties (e.g. for..in for enumerable only) and type checking instead of simply copying everything over. You usually end up needing to recurse on properties which are Objects themselves.
For known types, you can teach it to use the correct constructor too, e.g.
if (Array.isArray(o)) {
e = [];
o.forEach((v, i) => e[i] = recurse(v));
}
Where recurse would be the name of the clone function

Clone a function in Node.js [duplicate]

What is the best way to clone an object in node.js
e.g. I want to avoid the situation where:
var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
console.log(obj1.x); // logs 6
The object may well contain complex types as attributes, so a simple for(var x in obj1) wouldn't solve. Do I need to write a recursive clone myself or is there something built in that I'm not seeing?
Possibility 1
Low-frills deep copy:
var obj2 = JSON.parse(JSON.stringify(obj1));
Possibility 2 (deprecated)
Attention: This solution is now marked as deprecated in the documentation of Node.js:
The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.
It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().
Original answer::
For a shallow copy, use Node's built-in util._extend() function.
var extend = require('util')._extend;
var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5
Source code of Node's _extend function is in here: https://github.com/joyent/node/blob/master/lib/util.js
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
I'm surprised Object.assign hasn't been mentioned.
let cloned = Object.assign({}, source);
If available (e.g. Babel), you can use the object spread operator:
let cloned = { ... source };
Object.defineProperty(Object.prototype, "extend", {
enumerable: false,
value: function(from) {
var props = Object.getOwnPropertyNames(from);
var dest = this;
props.forEach(function(name) {
if (name in dest) {
var destination = Object.getOwnPropertyDescriptor(from, name);
Object.defineProperty(dest, name, destination);
}
});
return this;
}
});
This will define an extend method that you can use. Code comes from this article.
var obj2 = JSON.parse(JSON.stringify(obj1));
You can use the extend function from JQuery:
var newClone= jQuery.extend({}, oldObject);
var deepClone = jQuery.extend(true, {}, oldObject);
There is a Node.js Plugin too:
https://github.com/shimondoodkin/nodejs-clone-extend
To do it without JQuery or Plugin read this here:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Check out underscore.js. It has both clone and extend and many other very useful functions.
This can be useful: Using the Underscore module with Node.js
There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone
Looks like it handles all kinds of stuff, including circular references. From the github page:
clone masters cloning objects, arrays, Date objects, and RegEx
objects. Everything is cloned recursively, so that you can clone dates
in arrays in objects, for example. [...] Circular references? Yep!
There is another library lodash, it has clone and cloneDeep.
clone will clone your object but not create a new instance for non-primitive values, instead it will use the referrence to the original object
cloneDeep will create literally new objects without having any referrence to the original object, so it more safe when you have to change the object afterwards.
Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method
var a = {"a": "a11", "b": "avc"};
var b;
for(var keys = Object.keys(a), l = keys.length; l; --l)
{
b[ keys[l-1] ] = a[ keys[l-1] ];
}
b.a = 0;
console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"}
console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}
The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method
but of course for nested objects need to implement recursive func
Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one
var a = {"a": i, "b": i*i};
var b = JSON.parse(JSON.stringify(a));
b.a = 0;
This code is also work cause The Object.create() method creates a new object with the specified prototype object and properties.
var obj1 = {x:5, y:5};
var obj2 = Object.create(obj1);
obj2.x; //5
obj2.x = 6;
obj2.x; //6
obj1.x; //5
There is also a project on Github that aims to be a more direct port of the jQuery.extend():
https://github.com/dreamerslab/node.extend
An example, modified from the jQuery docs:
var extend = require('node.extend');
var object1 = {
apple: 0,
banana: {
weight: 52,
price: 100
},
cherry: 97
};
var object2 = {
banana: {
price: 200
},
durian: 100
};
var merged = extend(object1, object2);
Looking for a true clone option, I stumbled across ridcully's link to here:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:
Object.defineProperty(Object.prototype, 'clone', {
enumerable: false,
value: function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
}
});
Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.
You can also use SugarJS in NodeJS.
http://sugarjs.com/
They have a very clean clone feature:
http://sugarjs.com/api/Object/clone
If you're using coffee-script, it's as easy as:
newObject = {}
newObject[key] = value for own key,value of oldObject
Though this isn't a deep clone.
None of the answers satisfied me, several don't work or are just shallow clones, answers from #clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone
There is no built-in way to do a real clone (deep copy) of an object in node.js. There are some tricky edge cases so you should definitely use a library for this. I wrote such a function for my simpleoo library. You can use the deepCopy function without using anything else from the library (which is quite small) if you don't need it. This function supports cloning multiple data types, including arrays, dates, and regular expressions, it supports recursive references, and it also works with objects whose constructor functions have required parameters.
Here is the code:
//If Object.create isn't already defined, we just do the simple shim, without the second argument,
//since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
object_create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
/**
* Deep copy an object (make copies of all its object properties, sub-properties, etc.)
* An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
* that doesn't break if the constructor has required parameters
*
* It also borrows some code from http://stackoverflow.com/a/11621004/560114
*/
function deepCopy = function deepCopy(src, /* INTERNAL */ _visited) {
if(src == null || typeof(src) !== 'object'){
return src;
}
// Initialize the visited objects array if needed
// This is used to detect cyclic references
if (_visited == undefined){
_visited = [];
}
// Ensure src has not already been visited
else {
var i, len = _visited.length;
for (i = 0; i < len; i++) {
// If src was already visited, don't try to copy it, just return the reference
if (src === _visited[i]) {
return src;
}
}
}
// Add this object to the visited array
_visited.push(src);
//Honor native/custom clone methods
if(typeof src.clone == 'function'){
return src.clone(true);
}
//Special cases:
//Array
if (Object.prototype.toString.call(src) == '[object Array]') {
//[].slice(0) would soft clone
ret = src.slice();
var i = ret.length;
while (i--){
ret[i] = deepCopy(ret[i], _visited);
}
return ret;
}
//Date
if (src instanceof Date) {
return new Date(src.getTime());
}
//RegExp
if (src instanceof RegExp) {
return new RegExp(src);
}
//DOM Element
if (src.nodeType && typeof src.cloneNode == 'function') {
return src.cloneNode(true);
}
//If we've reached here, we have a regular object, array, or function
//make sure the returned object has the same prototype as the original
var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
if (!proto) {
proto = src.constructor.prototype; //this line would probably only be reached by very old browsers
}
var ret = object_create(proto);
for(var key in src){
//Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
//For an example of how this could be modified to do so, see the singleMixin() function
ret[key] = deepCopy(src[key], _visited);
}
return ret;
};
You can also use this clone library to deep clone objects.
npm install --save clone
const clone = require('clone');
const clonedObject = clone(sourceObject);
If you're working with ordinary objects and arrays, and don't care about cloning functions or recursive references, here's a simple deepClone implementation which works on ordinary objects, arrays, strings, numbers, regex, dates, etc.
// Simple Deep Clone
// Does not clone functions or handle recursive references.
function deepClone(original) {
if (original instanceof RegExp) {
return new RegExp(original);
} else if (original instanceof Date) {
return new Date(original.getTime());
} else if (Array.isArray(original)) {
return original.map(deepClone);
} else if (typeof original === 'object' && original !== null) {
const clone = {};
Object.keys(original).forEach(k => {
clone[k] = deepClone(original[k]);
});
return clone;
}
return original;
}
// Usage:
const obj = { n: 1, a: [ { a: 1 }, { a: 2 } ], d: new Date(), s: 'foo' };
const clone = deepClone(obj);
Good article about this problem: https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/
var obj1 = {x: 5, y:5};
var obj2 = Object.assign({}, obj1 );
obj2 = {z: 10};
console.log(obj1);
console.log(obj2);
Another solution is to encapsulate directly in the new variable using:
obj1= {...obj2}
You can prototype object and then call object instance every time you want to use and change object:
function object () {
this.x = 5;
this.y = 5;
}
var obj1 = new object();
var obj2 = new object();
obj2.x = 6;
console.log(obj1.x); //logs 5
You can also pass arguments to object constructor
function object (x, y) {
this.x = x;
this.y = y;
}
var obj1 = new object(5, 5);
var obj2 = new object(6, 6);
console.log(obj1.x); //logs 5
console.log(obj2.x); //logs 6
Hope this is helpful.

Copy object properties to a new one - not by reference

I have a JavaScript array of objects, which is initialised with some values.
I want to copy those values to a new array of objects, but without referencing to the original one, so I can then manipulate the new object.
I tried objectOptions.concat() like in this sample code but it then deletes also the referenced original object:
var objectOptions = [{option1: 'value1', someOption: 'value2'}];
function objectClean(){
var newObjectOptions = objectOptions.concat();
for(var i in newObjectOptions ) {
delete newObjectOptions[i]['someOption'];
}
return newObjectOptions ;
};
If your object is simple enough and JSON-compatible (i.e., only contains objects, arrays and primitives, no DOM references, no Regex objects, no circular references etc.), the simplest way to clone is:
var clone = JSON.parse(JSON.stringify(original));
Otherwise, you'll need a deep copy function, like the one found on this answer*:
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor(); // changed
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
* Be careful! The accepted answer to that question is a jQuery only solution, and terribly overrated!
var copyme = {/*object with properties which are to be copied in another object*/};
var copy = {};
for (var attr in copyme) {
if (copyme.hasOwnProperty(attr)) copy[attr] = clone(copyme[attr]);
}

Nodejs: how to clone an object

If I clone an array, I use cloneArr = arr.slice()
I want to know how to clone an object in nodejs.
For utilities and classes where there is no need to squeeze every drop of performance, I often cheat and just use JSON to perform a deep copy:
function clone(a) {
return JSON.parse(JSON.stringify(a));
}
This isn't the only answer or the most elegant answer; all of the other answers should be considered for production bottlenecks. However, this is a quick and dirty solution, quite effective, and useful in most situations where I would clone a simple hash of properties.
Object.assign hasn't been mentioned in any of above answers.
let cloned = Object.assign({}, source);
If you're on ES6 you can use the spread operator:
let cloned = { ... source };
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone
Looks like it handles all kinds of stuff, including circular references. From the github page:
clone masters cloning objects, arrays, Date objects, and RegEx
objects. Everything is cloned recursively, so that you can clone dates
in arrays in objects, for example. [...] Circular references? Yep!
You can use lodash as well. It has a clone and cloneDeep methods.
var _= require('lodash');
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
It's hard to do a generic but useful clone operation because what should be cloned recursively and what should be just copied depends on how the specific object is supposed to work.
Something that may be useful is
function clone(x)
{
if (x === null || x === undefined)
return x;
if (typeof x.clone === "function")
return x.clone();
if (x.constructor == Array)
{
var r = [];
for (var i=0,n=x.length; i<n; i++)
r.push(clone(x[i]));
return r;
}
return x;
}
In this code the logic is
in case of null or undefined just return the same (the special case is needed because it's an error to try to see if a clone method is present)
does the object have a clone method ? then use that
is the object an array ? then do a recursive cloning operation
otherwise just return the same value
This clone function should allow implementing custom clone methods easily... for example
function Point(x, y)
{
this.x = x;
this.y = y;
...
}
Point.prototype.clone = function()
{
return new Point(this.x, this.y);
};
function Polygon(points, style)
{
this.points = points;
this.style = style;
...
}
Polygon.prototype.clone = function()
{
return new Polygon(clone(this.points),
this.style);
};
When in the object you know that a correct cloning operation for a specific array is just a shallow copy then you can call values.slice() instead of clone(values).
For example in the above code I am explicitly requiring that a cloning of a polygon object will clone the points, but will share the same style object. If I want to clone the style object too instead then I can just pass clone(this.style).
There is no native method for cloning objects. Underscore implements _.clone which is a shallow clone.
_.clone = function(obj) {
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
It either slices it or extends it.
Here's _.extend
// extend the obj (first parameter)
_.extend = function(obj) {
// for each other parameter
each(slice.call(arguments, 1), function(source) {
// loop through all properties of the other objects
for (var prop in source) {
// if the property is not undefined then add it to the object.
if (source[prop] !== void 0) obj[prop] = source[prop];
}
});
// return the object (first parameter)
return obj;
};
Extend simply iterates through all the items and creates a new object with the items in it.
You can roll out your own naive implementation if you want
function clone(o) {
var ret = {};
Object.keys(o).forEach(function (val) {
ret[val] = o[val];
});
return ret;
}
There are good reasons to avoid deep cloning because closures cannot be cloned.
I've personally asked a question about deep cloning objects before and the conclusion I came to is that you just don't do it.
My recommendation is use underscore and it's _.clone method for shallow clones
For a shallow copy, I like to use the reduce pattern (usually in a module or such), like so:
var newObject = Object.keys(original).reduce(function (obj, item) {
obj[item] = original[item];
return obj;
},{});
Here's a jsperf for a couple of the options: http://jsperf.com/shallow-copying
Old question, but there's a more elegant answer than what's been suggested so far; use the built-in utils._extend:
var extend = require("util")._extend;
var varToCopy = { test: 12345, nested: { val: 6789 } };
var copiedObject = extend({}, varToCopy);
console.log(copiedObject);
// outputs:
// { test: 12345, nested: { val: 6789 } }
Note the use of the first parameter with an empty object {} - this tells extend that the copied object(s) need to be copied to a new object. If you use an existing object as the first parameter, then the second (and all subsequent) parameters will be deep-merge-copied over the first parameter variable.
Using the example variables above, you can also do this:
var anotherMergeVar = { foo: "bar" };
extend(copiedObject, { anotherParam: 'value' }, anotherMergeVar);
console.log(copiedObject);
// outputs:
// { test: 12345, nested: { val: 6789 }, anotherParam: 'value', foo: 'bar' }
Very handy utility, especially where I'm used to extend in AngularJS and jQuery.
Hope this helps someone else; object reference overwrites are a misery, and this solves it every time!
In Node.js 17.x was added the method structuredClone() to allow made a deep clone.
Documentation of reference: https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
I implemented a full deep copy. I believe its the best pick for a generic clone method, but it does not handle cyclical references.
Usage example:
parent = {'prop_chain':3}
obj = Object.create(parent)
obj.a=0; obj.b=1; obj.c=2;
obj2 = copy(obj)
console.log(obj, obj.prop_chain)
// '{'a':0, 'b':1, 'c':2} 3
console.log(obj2, obj2.prop_chain)
// '{'a':0, 'b':1, 'c':2} 3
parent.prop_chain=4
obj2.a = 15
console.log(obj, obj.prop_chain)
// '{'a':0, 'b':1, 'c':2} 4
console.log(obj2, obj2.prop_chain)
// '{'a':15, 'b':1, 'c':2} 4
The code itself:
This code copies objects with their prototypes, it also copy functions (might be useful for someone).
function copy(obj) {
// (F.prototype will hold the object prototype chain)
function F() {}
var newObj;
if(typeof obj.clone === 'function')
return obj.clone()
// To copy something that is not an object, just return it:
if(typeof obj !== 'object' && typeof obj !== 'function' || obj == null)
return obj;
if(typeof obj === 'object') {
// Copy the prototype:
newObj = {}
var proto = Object.getPrototypeOf(obj)
Object.setPrototypeOf(newObj, proto)
} else {
// If the object is a function the function evaluate it:
var aux
newObj = eval('aux='+obj.toString())
// And copy the prototype:
newObj.prototype = obj.prototype
}
// Copy the object normal properties with a deep copy:
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
if(typeof obj[i] !== 'object')
newObj[i] = obj[i]
else
newObj[i] = copy(obj[i])
}
}
return newObj;
}
With this copy I can't find any difference between the original and the copied one except if the original used closures on its construction, so i think its a good implementation.
I hope it helps
Depending on what you want to do with your cloned object you can utilize the prototypal inheritence mechanism of javascript and achieve a somewhat cloned object through:
var clonedObject = Object.create(originalObject);
Just remember that this isn't a full clone - for better or worse.
A good thing about that is that you actually haven't duplicated the object so the memory footprint will be low.
Some tricky things to remember though about this method is that iteration of properties defined in the prototype chain sometimes works a bit different and the fact that any changes to the original object will affect the cloned object as well unless that property has been set on itself also.
Objects and Arrays in JavaScript use call by reference, if you update copied value it might reflect on the original object.
To prevent this you can deep clone the object, to prevent the reference to be passed, using lodash library cloneDeep method
run command
npm install lodash
const ld = require('lodash')
const objectToCopy = {name: "john", age: 24}
const clonedObject = ld.cloneDeep(objectToCopy)
Try this module for complex structures, developed especially for nodejs - https://github.com/themondays/deppcopy
Works faster than JSON stringify and parse on large structures and supports BigInt.
for array, one can use
var arr = [1,2,3];
var arr_2 = arr ;
print ( arr_2 );
arr=arr.slice(0);
print ( arr );
arr[1]=9999;
print ( arr_2 );
How about this method
const v8 = require('v8');
const structuredClone = obj => {
return v8.deserialize(v8.serialize(obj));
};

Cloning an Object in Node.js

What is the best way to clone an object in node.js
e.g. I want to avoid the situation where:
var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
console.log(obj1.x); // logs 6
The object may well contain complex types as attributes, so a simple for(var x in obj1) wouldn't solve. Do I need to write a recursive clone myself or is there something built in that I'm not seeing?
Possibility 1
Low-frills deep copy:
var obj2 = JSON.parse(JSON.stringify(obj1));
Possibility 2 (deprecated)
Attention: This solution is now marked as deprecated in the documentation of Node.js:
The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.
It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().
Original answer::
For a shallow copy, use Node's built-in util._extend() function.
var extend = require('util')._extend;
var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5
Source code of Node's _extend function is in here: https://github.com/joyent/node/blob/master/lib/util.js
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
I'm surprised Object.assign hasn't been mentioned.
let cloned = Object.assign({}, source);
If available (e.g. Babel), you can use the object spread operator:
let cloned = { ... source };
Object.defineProperty(Object.prototype, "extend", {
enumerable: false,
value: function(from) {
var props = Object.getOwnPropertyNames(from);
var dest = this;
props.forEach(function(name) {
if (name in dest) {
var destination = Object.getOwnPropertyDescriptor(from, name);
Object.defineProperty(dest, name, destination);
}
});
return this;
}
});
This will define an extend method that you can use. Code comes from this article.
var obj2 = JSON.parse(JSON.stringify(obj1));
You can use the extend function from JQuery:
var newClone= jQuery.extend({}, oldObject);
var deepClone = jQuery.extend(true, {}, oldObject);
There is a Node.js Plugin too:
https://github.com/shimondoodkin/nodejs-clone-extend
To do it without JQuery or Plugin read this here:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Check out underscore.js. It has both clone and extend and many other very useful functions.
This can be useful: Using the Underscore module with Node.js
There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone
Looks like it handles all kinds of stuff, including circular references. From the github page:
clone masters cloning objects, arrays, Date objects, and RegEx
objects. Everything is cloned recursively, so that you can clone dates
in arrays in objects, for example. [...] Circular references? Yep!
There is another library lodash, it has clone and cloneDeep.
clone will clone your object but not create a new instance for non-primitive values, instead it will use the referrence to the original object
cloneDeep will create literally new objects without having any referrence to the original object, so it more safe when you have to change the object afterwards.
Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method
var a = {"a": "a11", "b": "avc"};
var b;
for(var keys = Object.keys(a), l = keys.length; l; --l)
{
b[ keys[l-1] ] = a[ keys[l-1] ];
}
b.a = 0;
console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"}
console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}
The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method
but of course for nested objects need to implement recursive func
Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one
var a = {"a": i, "b": i*i};
var b = JSON.parse(JSON.stringify(a));
b.a = 0;
This code is also work cause The Object.create() method creates a new object with the specified prototype object and properties.
var obj1 = {x:5, y:5};
var obj2 = Object.create(obj1);
obj2.x; //5
obj2.x = 6;
obj2.x; //6
obj1.x; //5
There is also a project on Github that aims to be a more direct port of the jQuery.extend():
https://github.com/dreamerslab/node.extend
An example, modified from the jQuery docs:
var extend = require('node.extend');
var object1 = {
apple: 0,
banana: {
weight: 52,
price: 100
},
cherry: 97
};
var object2 = {
banana: {
price: 200
},
durian: 100
};
var merged = extend(object1, object2);
Looking for a true clone option, I stumbled across ridcully's link to here:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:
Object.defineProperty(Object.prototype, 'clone', {
enumerable: false,
value: function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
}
});
Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.
You can also use SugarJS in NodeJS.
http://sugarjs.com/
They have a very clean clone feature:
http://sugarjs.com/api/Object/clone
If you're using coffee-script, it's as easy as:
newObject = {}
newObject[key] = value for own key,value of oldObject
Though this isn't a deep clone.
None of the answers satisfied me, several don't work or are just shallow clones, answers from #clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone
There is no built-in way to do a real clone (deep copy) of an object in node.js. There are some tricky edge cases so you should definitely use a library for this. I wrote such a function for my simpleoo library. You can use the deepCopy function without using anything else from the library (which is quite small) if you don't need it. This function supports cloning multiple data types, including arrays, dates, and regular expressions, it supports recursive references, and it also works with objects whose constructor functions have required parameters.
Here is the code:
//If Object.create isn't already defined, we just do the simple shim, without the second argument,
//since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
object_create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
/**
* Deep copy an object (make copies of all its object properties, sub-properties, etc.)
* An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
* that doesn't break if the constructor has required parameters
*
* It also borrows some code from http://stackoverflow.com/a/11621004/560114
*/
function deepCopy = function deepCopy(src, /* INTERNAL */ _visited) {
if(src == null || typeof(src) !== 'object'){
return src;
}
// Initialize the visited objects array if needed
// This is used to detect cyclic references
if (_visited == undefined){
_visited = [];
}
// Ensure src has not already been visited
else {
var i, len = _visited.length;
for (i = 0; i < len; i++) {
// If src was already visited, don't try to copy it, just return the reference
if (src === _visited[i]) {
return src;
}
}
}
// Add this object to the visited array
_visited.push(src);
//Honor native/custom clone methods
if(typeof src.clone == 'function'){
return src.clone(true);
}
//Special cases:
//Array
if (Object.prototype.toString.call(src) == '[object Array]') {
//[].slice(0) would soft clone
ret = src.slice();
var i = ret.length;
while (i--){
ret[i] = deepCopy(ret[i], _visited);
}
return ret;
}
//Date
if (src instanceof Date) {
return new Date(src.getTime());
}
//RegExp
if (src instanceof RegExp) {
return new RegExp(src);
}
//DOM Element
if (src.nodeType && typeof src.cloneNode == 'function') {
return src.cloneNode(true);
}
//If we've reached here, we have a regular object, array, or function
//make sure the returned object has the same prototype as the original
var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
if (!proto) {
proto = src.constructor.prototype; //this line would probably only be reached by very old browsers
}
var ret = object_create(proto);
for(var key in src){
//Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
//For an example of how this could be modified to do so, see the singleMixin() function
ret[key] = deepCopy(src[key], _visited);
}
return ret;
};
You can also use this clone library to deep clone objects.
npm install --save clone
const clone = require('clone');
const clonedObject = clone(sourceObject);
If you're working with ordinary objects and arrays, and don't care about cloning functions or recursive references, here's a simple deepClone implementation which works on ordinary objects, arrays, strings, numbers, regex, dates, etc.
// Simple Deep Clone
// Does not clone functions or handle recursive references.
function deepClone(original) {
if (original instanceof RegExp) {
return new RegExp(original);
} else if (original instanceof Date) {
return new Date(original.getTime());
} else if (Array.isArray(original)) {
return original.map(deepClone);
} else if (typeof original === 'object' && original !== null) {
const clone = {};
Object.keys(original).forEach(k => {
clone[k] = deepClone(original[k]);
});
return clone;
}
return original;
}
// Usage:
const obj = { n: 1, a: [ { a: 1 }, { a: 2 } ], d: new Date(), s: 'foo' };
const clone = deepClone(obj);
Good article about this problem: https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/
var obj1 = {x: 5, y:5};
var obj2 = Object.assign({}, obj1 );
obj2 = {z: 10};
console.log(obj1);
console.log(obj2);
Another solution is to encapsulate directly in the new variable using:
obj1= {...obj2}
You can prototype object and then call object instance every time you want to use and change object:
function object () {
this.x = 5;
this.y = 5;
}
var obj1 = new object();
var obj2 = new object();
obj2.x = 6;
console.log(obj1.x); //logs 5
You can also pass arguments to object constructor
function object (x, y) {
this.x = x;
this.y = y;
}
var obj1 = new object(5, 5);
var obj2 = new object(6, 6);
console.log(obj1.x); //logs 5
console.log(obj2.x); //logs 6
Hope this is helpful.

Categories

Resources