Vanilla JS only please
That is, its the output should be an object that only contains data, and ignores the original's methods/prototype. Complex data structures that inherit from the default Object
, like Array
, can be copied in a shallow manner, as references. The way I do it now is:
function shallowCopyObjectData(obj) {
output = {};
for (var i in item) {
output[i] = obj[i];
}
return output;
};
The other way I've seen is:
function shallowCopyObjectData(obj) {
return JSON.parse(JSON.stringify(obj));
};
What is the most performant way to do it?
I've made a running jsPerf to compare speeds. If you come up with a solution, please feel free to fork and add: http://jsperf.com/shallow-object-data-copy
Edit @Barmar: I know a similar question has already been posted, but it asked about the fastest way to clone an object, which implied a deep copy that keep the constructor, prototype, etc. This question asks about the fastest way to copy just the data in the top level
In order to make a shallow copy, you can use Object. assign . This will create entirely new copy.
Shallow copy is faster than Deep copy. Deep copy is slower than Shallow copy. 3. The changes made in the copied object also reflect the original object.
A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.
A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won't create copies of the child objects themselves.
The '=' operator then copies the reference rather than the object (and it works fine for a Value Type). The MemberwiseClone() function in the superclass System is used by default to achieve this behavior. This is referred to as "Shallow Copy". We use the Clone() method from the System.
The Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Properties in the target object will be overwritten by properties in the sources if they have the same key.
var obj = { a: 1, b: 2, };
var new_obj = Object.assign({}, obj);
console.log(new_obj); //{ a: 1, b: 2, }
console.log(new_obj == obj); //false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With