UNPKG

traverson

Version:

Hypermedia API/HATEOAS client for Node.js and the browser

36 lines (32 loc) 899 B
'use strict'; // TODO Maybe replace with https://github.com/Raynos/xtend // check browser build size, though. function mergeRecursive(obj1, obj2) { if (!obj1 && obj2) { obj1 = {}; } for (var key in obj2) { if (!obj2.hasOwnProperty(key)) { continue; } merge(obj1, obj2, key); } return obj1; } function merge(obj1, obj2, key) { if (typeof obj2[key] === 'object') { // if it is an object (that is, a non-leave in the tree), // and it is not present in obj1 if (!obj1[key] || typeof obj1[key] !== 'object') { // ... we create an empty object in obj1 obj1[key] = {}; } // and we recurse deeper into the structure mergeRecursive(obj1[key], obj2[key]); } else { // if it is primitive (string, number, boolean) or a function, we overwrite/ // add it to obj1 obj1[key] = obj2[key]; } } module.exports = mergeRecursive;