Search code examples
javascriptnode.jslodash

Is there a way to make lodash copy property getters and setters?


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?


Solution

  • 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.