4

In the following situation I am finding that lodash doesn't seem to copy the getter of the source object:

const _ = require("lodash");

let sourceObject = { };
Object.defineProperty(sourceObject, "abc", {
    get: () => 123
});

let cloneObject = _.cloneDeep(sourceObject);

console.log(sourceObject.abc); // 123
console.log(cloneObject.abc);  // undefined

Is there a way to achieve the above with the lodash module?

Lea Hayes
  • 62,536
  • 16
  • 62
  • 111

1 Answers1

5

Only if the defined property is enumerable. This will cause it to be detected with Object.keys() which is ultimately how lodash gets the list of property names. This is configurable when you define the property with the {enumerable: true} option, but it defaults to false, which is why _.cloneDeep isn't picking up your property.

See the MDN docs for Object.defineProperty for more details.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Awesome thanks for the super fast response!! works perfectly :D – Lea Hayes Dec 17 '15 at 06:27
  • 2
    It seems as if lodash deepClone will indeed find the getter if it is enumerable but will not make a copy of the getter in the new object. Instead it will access the value using the getter and clone that value raw. Resulting object clone seems to be missing the getter definition ??? – Moonwalker Dec 31 '15 at 16:17
  • 3
    Yes, getting the values is straightforward. Making a "true clone" for some definition of that is [complicated to put it mildly](http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object) – Peter Lyons Dec 31 '15 at 16:27
  • 2
    so reading the question, looks like it was about making a copy of the getter itself which cloneDeep is not capable of doing. Yet, your answer was accepted as working perfectly even though the solution does not clone the getter ..so go figure... :) I am struggling to find a method to deepClone an object that in its structure may contain basic getter.. – Moonwalker Jan 01 '16 at 12:31