UNPKG

@cch137/format-utils

Version:

A collection of utility modules for formatting and processing data

45 lines (44 loc) 1.73 kB
export function deepmerge(...objects) { const validObjects = objects.filter((obj) => obj != null); if (validObjects.length === 0) { return {}; } if (validObjects.length === 1) { return { ...validObjects[0] }; } const result = { ...validObjects[0] }; const prototypeOfArray = Object.getPrototypeOf([]); const prototypeOfObject = Object.getPrototypeOf({}); const isMergable = (o) => o && typeof o === "object" && Object.getPrototypeOf(o) === prototypeOfObject; const isArray = (o) => Array.isArray(o) && Object.getPrototypeOf(o) === prototypeOfArray; for (let i = 1; i < validObjects.length; i++) { const currentObj = validObjects[i]; for (const key in currentObj) { if (Object.prototype.hasOwnProperty.call(currentObj, key)) { const currentValue = currentObj[key]; const existingValue = result[key]; if (currentValue === null || currentValue === undefined) { result[key] = currentValue; continue; } if (isMergable(existingValue) && isMergable(currentValue)) { result[key] = deepmerge(existingValue, currentValue); } else { if (isArray(currentValue)) { result[key] = [...currentValue]; } else if (isMergable(currentValue)) { result[key] = { ...currentValue }; } else { result[key] = currentValue; } } } } } return result; }