Skip to content

Function: objCopy() ​

objCopy<Key, InValue, OutValue, IgnoredKey>(input, output?, ignoreKeys?, override?, recursive?): Record<PropertyKey, unknown>

Defined in: packages/core/src/obj/objCopy.ts:77

Deep-copy an object to another object

Type Parameters ​

Key ​

Key extends PropertyKey

InValue ​

InValue

OutValue ​

OutValue

IgnoredKey ​

IgnoredKey extends PropertyKey

Parameters ​

input ​

Record<Key, InValue>

input object

output? ​

Record<PropertyKey, OutValue>

(optional) output object

ignoreKeys? ​

Set<IgnoredKey> | IgnoredKey[]

(optional) input peroperties to be ignored. Prevents output's property to be overriden.

For child object properties use "." (dot) separated path.

Eg: "child.grandchild1" where input is { child: { grandchild1: 1, grandchild2: 2 }}

override? ​

boolean | "empty" | ((key, outputValue, inputValue) => boolean)

(optional) whether to allow override output properties. This will only be used if output object is provided and has own property. Accepted values:

  • true: input property will override output property
  • false: no overriding if output contains the property. Even if the property value is undefined.
  • "empty": only allow overriding output property if it's value is empty by using isEmpty.
  • function: decide whether to override on a per property basis.

Function Arguments: 1. key: current property name/key 2. outputValue: output property value 3. inputValue: input property value

Default: false

recursive? ​

boolean = true

(optional) whether to recursively copy nested objects. Default: false

Returns ​

Record<PropertyKey, unknown>

copied and/or merged object

Example ​

Copy or merge objects ​

javascript
import { objCopy } from '@superutils/core'

const source = {
	a: 1,
	b: 2,
	c: 3,
	x: {
		a: 1,
		b: 2,
	},
}
const dest = {
	d: 4,
	e: 5,
}
const copied = objCopy(
	source,
	dest,
	['a', 'x.b'], // exclude source property
	'empty', // only override if dest doesn't have the property or value is "empty" (check `is.emtpy()`)
	true, // recursively copies child objects. If false, child objects are copied by reference.
)
console.log({ copied })
// Result:
// {
//     b: 2,
//     c: 33,
//     d: 4,
//     e: 5,
// }
console.log(dest === copied) // true (dest is returned)