copy-own
Copies an object’s own properties to another object.
“Own” properties are those that are not inherited from the prototype chain.
Installation
Requires Node.js 6.0.0 or above.
npm i copy-own
API
The module exports a single function.
Parameters
from
(object): The source object that possesses the properties to be copied.- Optional:
to
(object): The destination object that should receive the copied properties. Defaults to a new object. - Optional: Object argument:
enumOnly
(boolean): Whether or not to limit the copy operation to only those properties that were defined with theenumerable
flag. Defaults tofalse
.override
(boolean): If omitted or set totrue
, all properties will be copied (unlessoverwrite
specifies otherwise). If set tofalse
, then existing properties into
will be neither overwritten nor overridden; that is, the copy operation will only include properties that do not share a name with properties already existing into
or in its prototype chain.overwrite
(boolean): This property is only taken into consideration ifoverride
(see above) is omitted or set totrue
. If this property is also omitted or set totrue
, all properties will be copied (the default behavior). If set tofalse
, then existing properties into
will not be overwritten, but properties higher up into
’s prototype chain could still be overridden.
Return Value
The function modifies the second argument (to
) and returns it. If to
is omitted, a new object is created and returned.
Examples
const copyOwn = const from = a: 'from' b: 'from'const to = b: 'to' c: 'to'const to = toa // 'from'tob // 'from'toc // 'to'
Here is the same example repeated with overwrite
set to false
:
const copyOwn = const from = a: 'from' b: 'from'const to = b: 'to' c: 'to'const to = toa // 'from'tob // 'to'toc // 'to'
When no destination object is specified, a new object is created:
const copyOwn = const from = a: 1 b: 2const to = toa // 1tob // 2