Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to get a shallow copy the data of an object?

Tags:

javascript

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

like image 936
AlexZ Avatar asked Jan 03 '15 02:01

AlexZ


People also ask

How do you make a shallow copy of an object?

In order to make a shallow copy, you can use Object. assign . This will create entirely new copy.

Which is faster shallow copy or deep 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.

What is a shallow copy programming?

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.

What is a shallow copy in Python?

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.

How do you shallow copy an object in C#?

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.


1 Answers

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
like image 155
Maris Avatar answered Oct 06 '22 18:10

Maris