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