mergeWith
sourceが持つ値をtargetオブジェクトにマージします。
プロパティをどのようにマージするかを指定するために、merge関数引数を定義してください。merge関数引数はtargetオブジェクトに設定される値を返す必要があります。
undefinedを返す場合、デフォルトで2つの値を深くマージします。深いマージでは、ネストされたオブジェクトや配列を次のように再帰的にマージします:
sourceとtargetのプロパティが両方ともオブジェクトまたは配列の場合、2つのオブジェクトと配列はマージされます。sourceのプロパティがundefinedの場合、targetのプロパティは上書きされません。
この関数はtargetオブジェクトを変更します。
インターフェース
typescript
function mergeWith<T extends Record<PropertyKey, any>, S extends Record<PropertyKey, any>>(
target: T,
source: S,
merge: (targetValue: any, sourceValue: any, key: string, target: T, source: S) => any
): T & S;パラメータ
target(T):sourceオブジェクトが持つプロパティをマージするオブジェクト。このオブジェクトは関数によって変更されます。source(S):targetオブジェクトにプロパティをマージするオブジェクト。merge((targetValue: any, sourceValue: any, key: string, target: T, source: S) => any): 2つの値をどのようにマージするかを定義する関数。以下の引数で呼び出されます:targetValue:targetオブジェクトが持つ値。sourceValue:sourceオブジェクトが持つ値。key: マージされているプロパティ名。target:targetオブジェクト。source:sourceオブジェクト。
戻り値
(T & S): sourceオブジェクトが持つプロパティがマージされたtargetオブジェクト。
例
typescript
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
mergeWith(target, source, (targetValue, sourceValue) => {
if (typeof targetValue === 'number' && typeof sourceValue === 'number') {
return targetValue + sourceValue;
}
});
// 戻り値: { a: 1, b: 5, c: 4 }
const target = { a: [1], b: [2] };
const source = { a: [3], b: [4] };
const result = mergeWith(target, source, (objValue, srcValue) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
});
// 戻り値: { a: [1, 3], b: [2, 4] })
