-
Notifications
You must be signed in to change notification settings - Fork 2
/
deepAssign.js
46 lines (40 loc) · 967 Bytes
/
deepAssign.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// values of the source object copied onto the target object
var objFoo = {
name: "Foo",
property: "Bar",
child: {
foo: "bar",
blah: [1, 2, 3, 4]
},
};
var objFighters = {
name: "Fighters",
property: "Barnone",
child: {
foo: "manchu",
additionally: "addme"
},
age: 15
};
// Result should equal
// {
// name: "Fighters",
// property: "Barnone",
// child: {
// foo: "manchu",
// additionally: "addme",
// blah: [1,2,3,4]
// },
// age: 15
function deepAssign(source, target) {
for (let key in source) {
if (typeof source[key] == "object" && !Array.isArray(source[key]) && target[key] !== undefined) {
target[key] = deepAssign(source[key], target[key]);
} else {
target[key] = source[key];
}
}
return target;
}
var result = deepAssign(objFighters, objFoo);
console.log('result', result);