Clone a nested Object

When we assign a nested object to a new property, the properties nested inside the object will remain linked. In some cases we can use the spread operator to create a whole new object but this will only work with 1 level of nested objects. In order to have a complete new instance of the object with no reference to the original object, we can use lodash _.cloneDeep() method.

Requirements: lodash

Examples:

var test = {
  user: {
    name: 'Roch',
    surname: 'Cassar',
    education: {
      primary: {},
      secondary: {},
      tertiary: {}
    }
  }
};

I can use the spread operator to get a new instance of user as follows:

var newUser = {...test.user};

The problem is that education will not be cloned but will still be referenced. To Avoid this, we can use cloneDeep by lodash.

var newUser = _.cloneDeep(test.user);