Skip to content

merge

sourceが持つ値をtargetオブジェクトにマージします。

この関数は深いマージを実行し、ネストされたオブジェクトや配列も再帰的にマージされます。

  • sourcetargetのプロパティが両方ともオブジェクトまたは配列の場合、2つのオブジェクトと配列はマージされます。
  • sourceのプロパティがundefinedの場合、targetのプロパティは上書きされません。

toMergedとは異なり、この関数はtargetオブジェクトを変更します。

インターフェース

typescript
function merge<T, S>(target: T, source: S): T & S;

パラメータ

  • target (T): sourceオブジェクトのプロパティをマージするオブジェクト。このオブジェクトは関数によって変更されます。
  • source (S): targetオブジェクトにプロパティをマージするオブジェクト。

戻り値

(T & S): sourceオブジェクトのプロパティがマージされたtargetオブジェクト。

typescript
const target = { a: 1, b: { x: 1, y: 2 } };
const source = { b: { y: 3, z: 4 }, c: 5 };
const result = merge(target, source);
console.log(result);
// 戻り値: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 }

const target = { a: [1, 2], b: { x: 1 } };
const source = { a: [3], b: { y: 2 } };
const result = merge(target, source);
console.log(result);
// 戻り値: { a: [3, 2], b: { x: 1, y: 2 } }

const target = { a: null };
const source = { a: [1, 2, 3] };
const result = merge(target, source);
console.log(result);
// 戻り値: { a: [1, 2, 3] }

デモ

import "./styles.css";

document.getElementById("app").innerHTML = `
<h1>Hello world</h1>
`;

パフォーマンス比較

Bundle SizePerformance
es-toolkit271 bytes (97.8% smaller)1,952,436 times (3.65× faster)
es-toolkit/compat4,381 bytes (64.9% smaller)706,558 times (1.32× faster)
lodash-es12,483 bytes533,484 times

MIT ライセンスの下で配布されています。