Skip to content

Instantly share code, notes, and snippets.

@ww24
Created March 24, 2012 11:59
Show Gist options
  • Save ww24/2181560 to your computer and use it in GitHub Desktop.
Save ww24/2181560 to your computer and use it in GitHub Desktop.
再帰的なオブジェクトのマージ
/*
* 再帰的なオブジェクトのマージ 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);
/*
* 再帰的なオブジェクトのマージ 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);
/*
* 再帰的なオブジェクトのマージ 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);
@ww24
Copy link
Author

ww24 commented Mar 24, 2012

ObjectだけではなくArrayも再帰的にマージします

@ww24
Copy link
Author

ww24 commented Mar 24, 2012

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