'What is the fastest way to get a shallow copy the data of an object?
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
Solution 1:[1]
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
Solution 2:[2]
Nowadays you can use spread just like;
var o = {a:1,b:2,c:3},
r = {...o}; // shallow clone
r.a = 11; // r's "a" property is set to 11
console.log(r); // check
console.log(o); // r is not a reference to a
Solution 3:[3]
You can use Object.assign to fast clone object. The syntax is Object. assign(originObject, extendObject). It will return the object that have property of originObject and extendObject.
For example I have the code here:
var originObject = {value: 1};
var extendObject = {key: 2};
var shadowObject = {};
// Now I want clone originObject to shadow object
shadowObject = Object. assign(originObject, {});
// shadowObject = {value: 1}
// If you want clone originObject and extendObject to one object
shadowObject = Object. assign(originObject, shadowObject);
// shadowObject = {value: 1, key: 2}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nircraft |
| Solution 2 | Dharman |
| Solution 3 | ross |
