From ada824fd8ebdb13e9abf4fd373a0b4a9876ab065 Mon Sep 17 00:00:00 2001 From: joshuaboud Date: Thu, 26 May 2022 14:46:43 -0300 Subject: [PATCH] add function to assign to nested objects with fallbacks --- .../src/functions/assignObjectRecursive.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 navigator-vue/src/functions/assignObjectRecursive.js diff --git a/navigator-vue/src/functions/assignObjectRecursive.js b/navigator-vue/src/functions/assignObjectRecursive.js new file mode 100644 index 0000000..8aa1c78 --- /dev/null +++ b/navigator-vue/src/functions/assignObjectRecursive.js @@ -0,0 +1,22 @@ +const isObject = (obj) => typeof obj === 'object' && !Array.isArray(obj) && obj !== null; + +/** + * Assign target to source with Object.assign(), filling in any missing properties from defaults + * + * @param {Object} target - target object + * @param {Object} source - source object + * @param {Object} defaults - fallback values if source is missing any properties + * @returns {Object} - the target object + */ +function assignObjectRecursive(target, source, defaults = {}) { + Object.assign(target, defaults, source); + for (const key in defaults) { + if (isObject(defaults[key]) && isObject(source[key])) { + target[key] = {}; + assignObjectRecursive(target[key], source[key], defaults[key]); + } + } + return target; +} + +export default assignObjectRecursive;