Cloning an Object with Lodash

Sep 20, 2019

Lodash's clone() function is a powerful utility for shallow cloning generic objects. The Object.assign() function or the spread operator are the canonical methods for shallow copying a POJO. But _.clone() has some additional functionality built in that may make it a better choice for your use case.

Cloning an Array

Object.assign() and _.clone() behave similarly when copying a plain old JavaScript object (POJO). But what about cloning an array?

const arr = ['a', 'b', 'c'];

// `Object.assign()` will copy all the array properties
// into a POJO
Object.assign({}, arr); // { '0': 1, '1': 2, '2': 3 }

// But `_.clone()` is smart enough to clone an array
_.clone(arr); // ['a', 'b', 'c']

Cloning an Instance of a Class

Another benefit of _.clone() is that the cloned object will have the same ES6 class as the original object. The Object.assign() function always returns a POJO.

class MyClass {
  constructor(val) {
    this.val = val;
  }
}

const obj = new MyClass(42);

// `Object.assign()` **always** returns a POJO. It
// doesn't actually create a new instance of the class.
Object.assign({}, obj) instanceof MyClass; // false

// `_.clone()` retains the original object's class.
_.clone(obj) instanceof MyClass; // true

Takeaways

If you need to clone a POJO, you don't need Lodash. Just use {...obj} or Object.assign({}, obj). But _.clone() is handy if you find yourself needing to clone class instances, or just want to be able to clone an arbitrary object without checking whether it is an array.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Lodash Tutorials