-
-
Save svlasov-gists/2383751 to your computer and use it in GitHub Desktop.
JavaScript: merge two objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function merge(target, source) { | |
/* Merges two (or more) objects, | |
giving the last one precedence */ | |
if ( typeof target !== 'object' ) { | |
target = {}; | |
} | |
for (var property in source) { | |
if ( source.hasOwnProperty(property) ) { | |
var sourceProperty = source[ property ]; | |
if ( typeof sourceProperty === 'object' ) { | |
target[ property ] = util.merge( target[ property ], sourceProperty ); | |
continue; | |
} | |
target[ property ] = sourceProperty; | |
} | |
} | |
for (var a = 2, l = arguments.length; a < l; a++) { | |
merge(target, arguments[a]); | |
} | |
return target; | |
}; |
Thanks, really Helped
function merge(target: { [x: string]: {} }, source: { [x: string]: {} }) {
/* Merges two (or more) objects,
giving the last one precedence */
if (typeof target !== "object") {
target = {};
}
for (const property in source) {
if (source.hasOwnProperty(property)) {
const sourceProperty = source[property];
if (typeof sourceProperty === "object" &&
// tslint:disable-next-line:no-null-keyword
sourceProperty !== null &&
sourceProperty.constructor !== Array
) {
target[property] = merge(target[property], sourceProperty);
continue;
}
target[property] = sourceProperty;
}
}
// tslint:disable-next-line:one-variable-per-declaration
for (let a = 2, l = arguments.length; a < l; a++) {
merge(target, arguments[a]);
}
return target;
}
// {} Ensures that there cannot be only 1 argument
merge({}, {}, ...sourceFixture);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
console.log(typeof null); - > "object"
console.log(typeof [1,2]); - > "object"
check only type enough