UNPKG

tricks

Version:
35 lines (31 loc) 910 B
import instanceOf from './instanceOf.js'; /** * Extend Object works like Object.assign(...) but recurses into the nested properties * With Array Index will merge objects within an array, extend treats them as being different and merely pushes them on to end of array * * @param {object} base - an object to extend * @param {...object} args - a series of objects to extend * @returns {object} extended object */ function extendWithArrayIndex(base, ...args) { args.forEach(o => { if (instanceOf(base, Object) && instanceOf(o, Object) && base !== o) { for (const x in o) { // Prevent prototype pollution if (x === '__proto__' || x === 'constructor') { continue; } base[x] = extendWithArrayIndex(base[x], o[x]); } } else if (Array.isArray(o)) { // Clone it base = o.slice(0); } else { base = o; } }); return base; } export default extendWithArrayIndex;