DEV Community

Discussion on: Copying objects in JavaScript

Collapse
 
bernardbaker profile image
Bernard Baker

Great article. Many of us encounter this problem and don't know how to resolve it. I've personally encountered it once or twice.

Collapse
 
ip127001 profile image
Rohit Kumawat • Edited

So there is a lodash library which gives cloneDeep() method to perfectly deep copy an object. Below an example attached:

var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);

You can also visit this page to find more: lodash.com/docs/4.17.15#cloneDeep

Another approach is to use recursion.
make a custom function like one I have used to iterate on each key in object and if that key is also an object then again call the method to copy the keys.
Something like below:


function isObject(obj) {
  let type = typeof obj;
  return type === 'object';
};

function deepCopy(obj) {
  let copiedObj = {};
  for (let key in obj) {
    if (obj.hasOwnkeyerty(key)) {
      if (isObject(obj[key])) {
        copiedObj[key] = deepCopy(obj[key]);
      } else {
        copiedObj[key] = obj[key];
      }
    }
  }
  return copiedObj;
}
Collapse
 
ag251994 profile image
abhishek gupta

I have stopped using lodash. I will use the recursive function

Collapse
 
papayankey profile image
Benneth Yankey • Edited

I surely will use the recursion approach too. However, typeof is sloppy in terms of differentiating between array and object. In order to truly check for object type, I will go with plain old trick below:

function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]';
}
Thread Thread
 
ip127001 profile image
Rohit Kumawat

Cool. I missed that part. Thanks for the solution.

I was just giving some information about how can we make such a function to deep copying with help of recursion. So, there might be some more improvements that can be implemented to make it handle every case.

But Great Insight!

Thread Thread
 
bernardbaker profile image
Bernard Baker

That's a good point.

Collapse
 
bernardbaker profile image
Bernard Baker

I like the recursive function.

Thread Thread
 
ip127001 profile image
Rohit Kumawat

Great! make your own common function to handle all cases.

Enjoy!