最近 javascriptを書く機会が少し増えてきたのでオブジェクトのマージ方法を備忘録的にメモ。
pure JS
通常のマージ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
var merge = function (obj1, obj2) {
if (!obj2) {
obj2 = {};
}
for (var attrname in obj2) {
if (obj2.hasOwnProperty(attrname)) {
obj1[attrname] = obj2[attrname];
}
}
};
var obj1 = {
name: 'pigmon',
city: 'tokyo',
tel: '00-0000-0000'
};
var obj2 = {
name: 'garamon',
city: 'osaka',
sex: 'man'
};
merge(obj1, obj2);
console.log(obj1);
// 実行結果
=> {name: "garamon", city: "osaka", tel: "00-0000-0000", sex: "man"}
|
存在しないプロパティのみマージ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
var merge = function (obj1, obj2) {
if (!obj2) {
obj2 = {};
}
for (var attrname in obj2) {
if (obj2.hasOwnProperty(attrname) && !obj1.hasOwnProperty(attrname)) {
obj1[attrname] = obj2[attrname];
}
}
};
var obj1 = {
name: 'pigmon',
city: 'tokyo',
tel: '00-0000-0000'
};
var obj2 = {
name: 'garamon',
city: 'osaka',
sex: 'man'
};
merge(obj1, obj2);
console.log(obj1);
// 実行結果
=> {name: "pigmon", city: "tokyo", tel: "00-0000-0000", sex: "man"}
|
JQuery(1.9.1)
通常のマージ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var obj1 = {
name: 'pigmon',
city: 'tokyo',
tel: '00-0000-0000'
};
var obj2 = {
name: 'garamon',
city: 'osaka',
sex: 'man'
};
$.extend(obj1, obj2);
console.log(obj1);
// 実行結果
=> {name: "garamon", city: "osaka", tel: "00-0000-0000", sex: "man"}
|
再帰的にマージ
extendの第一引数にtrueを与えると再帰的にマージしてくれる
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
var obj1 = {
name: 'pigmon',
address: {
city: 'tokyo',
tel: '00-0000-0000'
}
};
var obj2 = {
name: 'garamon',
address: {
city: 'osaka'
}
};
$.extend(true, obj1, obj2);
console.log(obj1);
// 実行結果
=> {name: "garamon", address: {city: "osaka", tel: "00-0000-0000"}}
|
underscore.js(1.4.3)
通常のマージ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
obj1 = {
name: 'pigmon',
city: 'tokyo',
tel: "00-0000-0000"
};
obj2 = {
name: 'garamon',
city: 'osaka',
sex: 'man'
};
_.extend(obj1, obj2);
console.log(obj1);
// 実行結果
=> {name: "garamon", city: "osaka", tel: "00-0000-0000", sex: "man"}
|
ちなみにunderscore.jsでは再帰的にマージはしてくれないよう。
これを見てるとできてるっぽいんだけど…
参考
jQuery.extend()
underscorejs extend