pvorb / clone Goto Github PK
View Code? Open in Web Editor NEWdeeply clone arbitrary objects in javascript
Home Page: https://www.npmjs.com/package/clone
License: MIT License
deeply clone arbitrary objects in javascript
Home Page: https://www.npmjs.com/package/clone
License: MIT License
Try these examples
abc = {
arr1: [
{
a: '1234',
b: '2345'
}
],
arr2: [
{
c: '345',
d: '456'
}
]
};
log(abc);
abc2 = clone(abc);
log(abc2);
log(_(abc).isEqual(abc2)); // false
log(abc) returns
{ arr1: [ { a: '1234', b: '2345' } ],
arr2: [ { c: '345', d: '456' } ] }
log(abc2) returns
{ arr1: { '0': { a: '1234', b: '2345' } },
arr2: { '0': { c: '345', d: '456' } } }
Maybe you can incorporate this code http://coffeescriptcookbook.com/chapters/classes_and_objects/cloning
Hi,
I'm currently creating an RPM for Enterprise Linux. Is it possible to change the license type to MIT, ISC or BSD? It will create a more flexible use, IMO. Thanks for letting me know. For more details, read this thread:
https://www.axivo.com/threads/ghost-setup.68/
When I try to clone an object that has getter methods defined, this lib seems to be calling those getters rather than coping the function :S
At next page ,the latest version is 2.1.1
https://www.npmjs.com/package/clone
can you alter it to 2.1.2?
At npm clone website the build is failing .
Seems like you used travis-ci.org/pvorb/node-clone/
instead of travis-ci.org/pvorb/clone
.
Consider the following example:
var o = {};
Object.defineProperty(o, 'foo', {enumerable:true, writable:false, value:'f'});
var o2 = clone(o);
console.log(Object.getOwnPropertyDescriptor(o2, 'foo'));
The property descriptor on the copied object specifies the property as writable
even though the original property wasn't writable.
If our Array.prototype contains custom functions then after cloning these functions are put directly to clonned array.
This later causes some problems because they arent meant to be there.
Rather than coping the getter method to the clone, it looks like the result of the getter is copied in.
var test = {
a: "world",
get b(){ return "hello" + this.a; }
};
var cloned = clone(test);
console.log("Original: ", test);
console.log("Cloned: ", cloned);
Yields
Original: { a: ' world', b: [Getter] }
Cloned: { a: ' world', b: 'hello world' }
When cloning an objects child, where the child value is an array. Clone will always return the child array as an object.
var data = {
"note" : {
"topics" : ["topic 1","topic 2"]
}
};
var noteTopics = data.note.topics;
var tempNoteTopics = Clone(noteTopics);
// returns an object...
// {
// "0" : "topic 1",
// "1" : "topic 2"
// }
This should be an array.
I have a custom class that extends from Map. This class is "DefaultMap", and provides a default value when an item is not found in the Map.
It looks like instances of "DefaultMap" are getting cloned as just "Map". It then loses the custom functionality provided by "DefaultMap".
Here's a test case in Mocha to reproduce the problem:
const assert = require('assert');
const clone = require('clone');
describe(`clone`, function () {
it(`can deep copy a class that extends map`, function () {
let overridingMethodWasCalled = false;
class DefaultMap extends Map {
constructor(defaultValueFactory, iterable) {
super(iterable);
this.defaultValueFactory = defaultValueFactory;
}
get(key) {
overridingMethodWasCalled = true;
if (!this.has(key)) {
const value = this.defaultValueFactory(key, this);
this.set(key, value);
return value;
} else {
return super.get(key);
}
}
}
const defaultValue = 'placeholder';
const map = new DefaultMap(() => defaultValue);
const obj = {
myMap: map
};
const copiedObj = clone(obj);
console.log(obj, copiedObj);
assert.notStrictEqual(obj.myMap, copiedObj.myMap, "Properties holding Maps should not reference the same object in memory");
assert.strictEqual(obj.myMap.size, copiedObj.myMap.size, "The cloned Map should have the same size as the original Map");
const value = copiedObj.myMap.get('nonExistentKey');
assert.ok(overridingMethodWasCalled, "The overriding method on DefaultMap should be called");
assert.strictEqual(value, defaultValue, "The cloned Map should be a DefaultMap, and should return the default value when given a non-existent key");
assert.notStrictEqual(obj.myMap.size, copiedObj.myMap.size, "After implicitly inserting an element, the cloned Map should have a different size to the original Map");
});
});
The test fails at the assertion "The overriding method on DefaultMap should be called".
Tested in clone v2.1.1, Node v6.9.1.
var clone = require('clone');
var obj = {}
var obj2 = { a: obj, b: obj };
var noFlagClone = clone(obj2);
console.log( noFlagClone.a === noFlagClone.b ); //true
var withFlagClone = clone(obj2, false);
console.log( withFlagClone.a === withFlagClone.b ); //false
TypeError: Cannot set property listening of #<Server> which has only a getter
at _clone (.../node_modules/clone/clone.js:156:16)
require('clone')(new Float32Array([10,11]))
Float32Array { '0': 10, '1': 11 } // actual
Float32Array [ 10, 11 ] // expected
Similar to #1, but for typed arrays.
The html test files are being published to npm as they are not in the .npmignore
file.
Please commit minified version of files for CDN unpkg.
I am using gulp-minify-css which uses this library. I've narrowed down an issue I'm getting after a recent update to clone. On clone v0.1.11 things run fine, but updating to 0.1.13 I get the following error:
gulp: ../src/node_object_wrap.h:61: static T* node::ObjectWrap::Unwrap(v8::Handle<v8::Object>) [with T = node::Buffer]: Assertion `handle->InternalFieldCount() > 0' failed.
I'm not sure what could be causing this or if this is the right place for the bug. My apologies if this isn't the correct project to report this bug.
$ node --version
v0.10.15
# Also happens on v0.10.26
When debugging this seems to crash on jquery objects/htmlelement for a unknown reason. I am using webpack.
I have switched to https://github.com/dbencic/deepclone and si far its working.
Unzip clone-issue.zip
and:
npm install
./node_modules/.bin/browserify test.js > bundle.js
chromium-browser test.html
Got:
bundle.js:2206 Uncaught TypeError: Illegal invocation
at _clone (bundle.js:2206)
at clone (bundle.js:2246)
at Object.30.clone (bundle.js:3077)
at o (bundle.js:1)
at r (bundle.js:1)
at bundle.js:1
The readme doesn't seem to make it to npm, which is inconvenient. Would be nice to see the contents there rather than having to come through to github.
Hi, seems like there is a typo in your example, it should be using require('node-clone')?
The official version of 1.0.1 has the following:
if (global.TESTING) clone.getRegExpFlags = getRegExpFlags;
if (global.TESTING) clone.objectToString = objectToString;
if (global.TESTING) clone.isDate = isDate;
if (global.TESTING) clone.isArray = isArray;
if (global.TESTING) clone.isRegExp = isRegExp;
and there is still the crash from #41
I don't know what global.TESTING is for, but I think there is something wrong with it. Please can you fix?
It only clones the source of a regular expression, not its flags or lastIndex
given this object:
var x = {
"Desc" : "Lorem ipsum dolor...",
"Features" : [],
"Id" : "WC"
};
if you were to do:
var y = clone(x);
console.log(y);
you would get:
{
"Desc" : "Lorem ipsum dolor...",
"Features" : []
}
Hi, I am installing node-clone through "npm install node-clone", but the clone.js I got has different content from the head version:
//Universal js Clone function (we think...)
//Works for any js object
var FN=function(fn) {
this.clone=fn;
};
exports.Clone=function(fn) {return new FN(fn).clone;};
Any idea what went wrong?
"use strict";
var clone = require("clone");
function Foo() {}
Foo.prototype.prop = 1;
var a = new Foo;
a.prop = 2;
var b = clone(a);
console.log(a, b);
Hello,
please tell if this is a bug. When parent object has an own and an inherited property with the same name, then the cloned one will not have the own one copied. This works correct if we have only an own or only an inherited one on the parent.
The clone function is appending functions to my code. My code looks like this
console.log(script)
let input = clone(script)
console.log('----------------')
console.log(input)
process.exit(0)
and outputs this (this first data is the input, the data below ---------- is the output). The output
has list data (I think appended to it)
{ data:
[ { pattern: [Array],
response: [Array],
details: [Object],
intent: [Array],
phraseClass: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] } ] }
----------------
{ data:
[ { pattern: [Array],
response: [Array],
details: [Object],
intent: [Array],
phraseClass: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
{ pattern: [Array], intent: [Array] },
__class__: { [Function: list] __name__: 'list' },
__iter__: [Function],
__getslice__: [Function],
__setslice__: [Function],
__repr__: [Function],
__str__: [Function],
append: [Function],
clear: [Function],
extend: [Function],
insert: [Function],
remove: [Function],
index: [Function],
py_pop: [Function],
py_sort: [Function],
__add__: [Function],
__mul__: [Function],
__rmul__: [Function],
__bindexOf__: [Function],
add: [Function],
discard: [Function],
isdisjoint: [Function],
issuperset: [Function],
issubset: [Function],
union: [Function],
intersection: [Function],
difference: [Function],
symmetric_difference: [Function],
py_update: [Function],
__eq__: [Function],
__ne__: [Function],
__le__: [Function],
__ge__: [Function],
__lt__: [Function],
__gt__: [Function] ] }
Is this the intended result? How do I get rid of the extra 'list' data?
function cloneObject(source) {
var key,value;
var clone = Object.create(source);
for (key in source) {
if (source.hasOwnProperty(key) === true) {
value = source[key];
if (value!==null && typeof value==="object") {
clone[key] = cloneObject(value);
} else {
clone[key] = value;
}
}
}
return clone;
}
Works with instanceof
, has the prototype
, and has enumerable keys.
Example:
const s = Symbol();
const a = {
[s]: 'hello'
};
const b = clone(a);
console.log(a[s]); // => hello
console.log(b[s]); // => undefined
It's probably caused by the fact that Symbol
properties are not enumerable as the normal property names. So, we don't get it by for (var i in parent)
on line 90 of clone.js.
If you have circular references in your Objects, the stack blows up. I have an idea on how to support circular references. Would you accept a pull request?
Currently when trying to clone an ES2015 Map object, I get an empty object returned.
const error = new Error('hhhhhh');
console.log(error);
/*
Error: hhhhhh
at Object.<anonymous> (/Users/miserylee/Documents/projects/com.whxxcy.8ddao/test.js:3:15)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (bootstrap_node.js:352:7)
at startup (bootstrap_node.js:144:9)
at bootstrap_node.js:467:3
*/
console.log(clone(error));
/*
[Error]
*/
โ
When copying a DOM object, following line fails:
child[i] = _clone(parent[i], depth - 1);
Line 156 in e3f252d
TypeError: The HTMLDivElement.align setter can only be used on instances of HTMLDivElement
It seems like calling Object.getPrototypeOf
on a DOM element gives HTMLDivElementPrototype
which has a slightly different behavior than HtmlDivElement
.
Reproducible in Safari Version 10.0 (10602.1.50.0.10)
Getting this with the latest version of clone (0.3.13), in Mac OSX and Linux, running node 0.10.x.
I don't actually use clone, but dependencies on my project do - and it's breaking all the Travis builds.
Here's the specific stack-trace I get: http://d.pr/i/YBKP
Here's the line that calls clone in gulp-minify-css: https://github.com/jonathanepollack/gulp-minify-css/blob/master/index.js#L39
Let me know if there's anything I can do to help or to test.
Thanks.
With the release 1.0.4 the latest npm version is marked now as 1.0.4, see here. I think that the latest should remain 2.1.1. Maybe you can fix using the following command:
npm dist-tag rm clone latest
npm dist-tag add [email protected] latest
See https://docs.npmjs.com/cli/dist-tag.
thanks
When I try to use clone() to clone an mongoose array or mongoose object in my application,
when try to clone mongoose object...
/home/kitz/myProject/node_modules/mongoose/lib/types/embedded.js:65
this.__parentArray._markModified();
^
TypeError: undefined is not a function
at EmbeddedDocument.markModified (/home/kitz/myProject/node_modules/mongoose/lib/types/embedded.js:65:24)
at EmbeddedDocument.Document.$__set (/home/kitz/myProject/node_modules/mongoose/lib/document.js:665:10)
at EmbeddedDocument.Document.set (/home/kitz/myProject/node_modules/mongoose/lib/document.js:603:10)
at EmbeddedDocument.Object.defineProperty.set [as _id] (/home/kitz/myProject/node_modules/mongoose/lib/document.js:1421:45)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:16)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at clone (/home/kitz/myProject/node_modules/clone/clone.js:105:10)
at Object.Util.clone (/home/kitz/myProject/libs/util.js:38:9)
at model.SomeSchema.methods.someFunc (/home/kitz/myProject/models/some.js:238:23)
at /home/kitz/myProject/models/some.js:418:22
at /home/kitz/myProject/node_modules/mongoose/lib/query.js:1173:16
when try to clone mongoose array...
/home/kitz/myProject/node_modules/mongoose/lib/document.js:1153
if (!this.$__.validationError) {
^
TypeError: Cannot read property 'validationError' of undefined
at model.Document.invalidate (/home/kitz/myProject/node_modules/mongoose/lib/document.js:1153:16)
at EmbeddedDocument.invalidate (/home/kitz/myProject/node_modules/mongoose/lib/types/embedded.js:177:19)
at EmbeddedDocument.Document.set (/home/kitz/myProject/node_modules/mongoose/lib/document.js:597:10)
at EmbeddedDocument.Object.defineProperty.set [as _id] (/home/kitz/myProject/node_modules/mongoose/lib/document.js:1421:45)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:16)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
at clone (/home/kitz/myProject/node_modules/clone/clone.js:105:10)
at Object.Util.clone (/home/kitz/myProject/libs/util.js:29:9)
at model.SomeSchema.methods.someFunc (/home/kitz/myProject/models/some.js:238:25)
Just a thought, support for ES6 modules could be added by adding one line to the last if
block of clone.js
like so:
if (typeof module === 'object' && module.exports) {
module.exports = clone;
module.exports.default = clone;
}
clone(element, true)
TypeError: Cannot set property firstChild of # which has only a getter
Add support for Promises (Node 0.12+). Someting like:
if (typeof Promise === 'function' && value instanceof Promise) {
clone = new Promise(function(fulfill, reject) {
value.then(function(result) {
fulfill(clone(result));
}, function(reason) {
reject(clone(reason));
});
});
}
I see a major
version change from 1.x -> 2.x. Assuming this repo follows semver semantics, what breaking change was introduced?
Thanks for your time on this project.
File
object from <input type='file'>
TypeError: Cannot assign to read only property 'size' of object '#<File>'
at _clone (clone.js:156)
at _clone (clone.js:156)
at _clone (clone.js:156)
at _clone (clone.js:156)
at _clone (clone.js:156)
at _clone (clone.js:156)
at clone (clone.js:196)
at LogEntry.set (LogEntry.js:148)
clone = require 'clone'
clone({regex: /^hello/})
TypeError: Object function clone(parent, circular, depth, prototype) {
....
} has no method 'getRegExpFlags'
From this:
child = new RegExp(parent.source, clone.getRegExpFlags(parent));
...
if (global.TESTING) clone.getRegExpFlags = getRegExpFlags;
There doesn't appear to be a tag so shrinkwrap is failing for me.
[TypeError: Cannot set property headerSent of # which has only a getter]
I get above error when clone current context HTTP request
Any suggestion please
Check if it works in browsers.
I use bunyan in my classes:
let bunyan = require('bunyan');
function MyClass() {
this.logger = bunyan.createLogger(...);
}
let m = new MyClass()
clone(m, true);
TypeError: Cannot set property remoteAddress of #<Socket> which has only a getter
at _clone (.../node_modules/clone/clone.js:99:16)
Thanks
I've just been looking at the code for clone and trying to work out if I can use the 4th param (prototype) to provide a predicate to determine if a property/array element should be cloned. I don't think that it can.
I'm looking to clone an object and to provide that clone function with a predicate that will continue the recursion and copying of properties if the predicate returns true against that object.
For example, let's say I have an object that I want to clone but don't want to clone any properties that have values of null or undefined.
your module isn't compatible with the strict mode. i get this stack trace:
function _clone(parent, context, child, cIndex) {
^^^^^^^^
SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/michael.heuberger/projects/binarykitchen/code/videomail/app/lib/boot/settings.js:2:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
can you make it work for the strict mode? thanks!
It appears that Node.js SecureContext
does not like getOwnPropertyDescriptor
called on it.
TypeError: Method _external called on incompatible receiver #<SecureContext>
at Function.getOwnPropertyDescriptor (<anonymous>)
at _clone (/var/task/node_modules/clone/clone.js:156:24)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.