Created
January 28, 2017 06:27
-
-
Save asm-jaime/a761e0c66d3df99cb7b191ae18b43b86 to your computer and use it in GitHub Desktop.
ways to merge objects (javascript)
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
'use strict'; | |
function merge_arguments() { | |
let obj = {}, | |
i = 0, | |
len = arguments.length, | |
key; | |
for (; i < len; i++) { | |
for (key in arguments[i]) { | |
if (arguments[i].hasOwnProperty(key)) { | |
obj[key] = arguments[i][key]; | |
} | |
} | |
} | |
return obj; | |
}; | |
function merge_recursive(first, second) { | |
for (let n in second) { | |
if (typeof first[n] != 'object') { | |
first[n] = second[n]; | |
} else if (typeof second[n] == 'object') { | |
first[n] = merge_recursive(first[n], second[n]); | |
} | |
}; | |
return first; | |
}; | |
const data_null = { | |
null_key: 'null', | |
}; | |
const data_first = { | |
first_key: 'foo', | |
tree_key: { | |
one: 1, | |
three: 3, | |
} | |
}; | |
const data_second = { | |
second_key: 'bar', | |
tree_key: { | |
one: 0, | |
two: 2, | |
} | |
}; | |
const res_spread = {...data_first, ...data_second}; | |
const res_assign = Object.assign({}, data_first, data_second); | |
const res_jquery = $.extend({}, data_first, data_second); | |
const res_json = JSON.parse((JSON.stringify(data_first) + JSON.stringify(data_second)).replace(/\}\{/, ', ')); | |
const res_arguments = merge_arguments({}, data_null, data_first, data_second); | |
const res_recursive = merge_recursive(data_first, data_second); | |
console.log('spread:'); | |
console.log(res_spread); | |
console.log('assign:'); | |
console.log(res_assign); | |
console.log('jquery:'); | |
console.log(res_jquery); | |
console.log('JSON:'); | |
console.log(res_json); | |
console.log('merge_arguments:'); | |
console.log(res_arguments); | |
console.log('merge_recursive:'); | |
console.log(res_recursive); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment