What is merge-descriptors?
The merge-descriptors npm package is a utility that allows you to copy enumerable properties from one or more source objects to a destination object, optionally defining property descriptors. It is commonly used to mix properties and their descriptors from one object into another, preserving more detailed configuration than a simple object spread or Object.assign.
What are merge-descriptors's main functionalities?
Merge properties with descriptors
This feature allows you to merge properties from the source object to the target object, including their getters and setters. The example shows how a property with a getter is copied to the target object, preserving its behavior.
const mergeDescriptors = require('merge-descriptors');
let target = {};
let source = { get foo() { return 'bar'; } };
mergeDescriptors(target, source);
console.log(target.foo); // Outputs: 'bar'
Merge properties without overwriting
This feature demonstrates how to merge properties without overwriting existing properties in the target object. The example merges a getter for 'foo' from the source into the target, but since 'foo' already exists in the target and the overwrite flag is set to false, the original value is preserved.
const mergeDescriptors = require('merge-descriptors');
let target = { foo: 'initial' };
let source = { get foo() { return 'bar'; } };
mergeDescriptors(target, source, false);
console.log(target.foo); // Outputs: 'initial'
Other packages similar to merge-descriptors
lodash.merge
Lodash's merge function is similar to merge-descriptors but focuses more on deep merging of properties, including arrays and plain objects. Unlike merge-descriptors, lodash.merge does not handle property descriptors, making it less suitable for cases where property getters, setters, or other descriptor specifics are crucial.
object-assign
The object-assign package provides a function to copy values of all enumerable own properties from one or more source objects to a target object. It is similar to Object.assign() and does not copy property descriptors, making merge-descriptors a better choice when descriptors need to be preserved.
merge-descriptors
Merge objects using their property descriptors
Install
npm install merge-descriptors
Usage
import mergeDescriptors from 'merge-descriptors';
const thing = {
get name() {
return 'John'
}
}
const animal = {};
mergeDescriptors(animal, thing);
console.log(animal.name);
API
merge(destination, source, overwrite?)
Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties.
Returns the modified destination object.
destination
Type: object
The object to receive properties.
source
Type: object
The object providing properties.
overwrite
Type: boolean
Default: true
A boolean to control overwriting of existing properties.