UNPKG

@adobe/adobe-client-data-layer

Version:
65 lines (55 loc) 2.21 kB
/* Copyright 2020 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const _ = require('../../custom-lodash'); const cloneDeepWith = _.cloneDeepWith; const isObject = _.isObject; const isArray = _.isArray; const reject = _.reject; const mergeWith = _.mergeWith; const isNull = _.isNull; /** * Merges the source into the object and sets objects as 'undefined' if they are 'undefined' in the source object. * * @param {Object} object The object into which to merge. * @param {Object} source The source to merge with. * @returns {Object} The object into which source was merged in. */ module.exports = function(object, source) { const makeOmittingCloneDeepCustomizer = function(predicate) { return function omittingCloneDeepCustomizer(value, key, object, stack) { if (isObject(value)) { if (isArray(value)) { return reject(value, predicate).map(item => cloneDeepWith(item, omittingCloneDeepCustomizer)); } const clone = {}; for (const subKey of Object.keys(value)) { if (!predicate(value[subKey])) { clone[subKey] = cloneDeepWith(value[subKey], omittingCloneDeepCustomizer); } } return clone; } return undefined; }; }; const customizer = function(objValue, srcValue, key, object) { if (typeof srcValue === 'undefined' || srcValue === null) { return null; } }; const omitDeep = function(value, predicate = (val) => !val) { return cloneDeepWith(value, makeOmittingCloneDeepCustomizer(predicate)); }; mergeWith(object, source, customizer); // Remove null or undefined objects object = omitDeep(object, isNull); return object; };