Skip to content

cloneDeep maintains reference after cloning? #2725

@hulbert

Description

@hulbert

Not sure if this is intended, it doesn't match what I use _.cloneDeep for but perhaps it's desired for other cases. It came up unexpectedly in our codebase so I'd be curious—if it's intended behavior—if it could be documented clearly.

It seems that _.cloneDeep maintains, in the cloned object, two keys referencing the same object in the original object.

Example case:

'use strict'

let _ = require('lodash')

let x = { lodash: 'isgreat' }

let y = { 
    one: x,
    two: x,
    three: { 
        javascript: 'isfun' 
    }
}

console.log('One and two are equal in original object?', y.one === y.two)

let yy = _.cloneDeep(y)

console.log('One and two are equal in deep cloned object?', yy.one === yy.two)
console.log('One is different object before and after clone?', y.one === yy.one)

This prints:

One and two are equal in original object? true
One and two are equal in deep cloned object? true
One is different object before and after clone? false

I would have expected it to print:

One and two are equal in original object? true
One and two are equal in deep cloned object? false
One is different object before and after clone? false

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions