Created
March 24, 2012 11:59
-
-
Save ww24/2181560 to your computer and use it in GitHub Desktop.
再帰的なオブジェクトのマージ
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
/* | |
* 再帰的なオブジェクトのマージ 1 (クロスブラウザ) | |
*/ | |
var merge = function merge(a, b) { | |
for (key in b) { | |
if (b.hasOwnProperty(key)) { | |
a[key] = (key in a) | |
? ((typeof a[key] === "object" && typeof b[key] === "object") | |
? merge(a[key], b[key]) : b[key]) : b[key]; | |
} | |
} | |
return a; | |
}; | |
// Usage | |
var obj = { | |
hoge: "hogehoge", | |
piyo: [ | |
"ピヨ", | |
"piyopiyo" | |
] | |
}; | |
obj = merge(obj, {test: "hello", piyo: ["piyo"]}); | |
console.log(obj); |
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
/* | |
* 再帰的なオブジェクトのマージ 2 | |
*/ | |
var merge = function merge(a, b) { | |
Object.keys(b).forEach(function (key) { | |
a[key] = (key in a) | |
? ((typeof a[key] === "object" && typeof b[key] === "object") | |
? merge(a[key], b[key]) : b[key]) : b[key]; | |
}); | |
return a; | |
}; | |
// Usage | |
var obj = { | |
hoge: "hogehoge", | |
piyo: [ | |
"ピヨ", | |
"piyopiyo" | |
] | |
}; | |
obj = merge(obj, {test: "hello", piyo: ["piyo"]}); | |
console.log(obj); |
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
/* | |
* 再帰的なオブジェクトのマージ 3 (for Node.js 最適化) | |
* 参考URL: http://d.hatena.ne.jp/hokaccha/20110728/1311866555 | |
*/ | |
function merge() { | |
return [].reduce.call(arguments, function merge(a, b) { | |
Object.keys(b).forEach(function (key) { | |
a[key] = (typeof a[key] === "object" && typeof b[key] === "object") | |
? a[key] = merge(a[key], b[key]) : a[key] = b[key]; | |
}); | |
return a; | |
}); | |
} | |
// Usage | |
var obj = { | |
hoge: "hogehoge", | |
piyo: [ | |
"ピヨ", | |
"piyopiyo" | |
] | |
}; | |
obj = merge(obj, {test: "hello", piyo: ["piyo"]}); | |
console.log(obj); | |
var a = {hoge: {key1: 'val1'}}; | |
var b = {hoge: {key2: 'val2'}}; | |
var c = {hoge: {key1: 'val3'}}; | |
obj = merge(a, b, c); | |
console.log(obj); |
recursive-object-merge.jsはブラウザで使う場合
rom1.jsは(Array.prototype.forEachが使える)新しいブラウザで使う場合
rom2.jsは引数に可変長のオブジェクトを渡す事ができる
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ObjectだけではなくArrayも再帰的にマージします