-
Notifications
You must be signed in to change notification settings - Fork 5
/
merge.js
41 lines (39 loc) · 1.01 KB
/
merge.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
'use strict'
const merge = (target, src) => {
const isArray = Array.isArray(src)
let destination = isArray && [] || {}
if (isArray) {
target = target || []
destination = destination.concat(target)
src.forEach((e, i) => {
if (typeof destination[i] === 'undefined') {
destination[i] = e
} else if (typeof e === 'object') {
destination[i] = merge(target[i], e)
} else {
if (target.indexOf(e) === -1) {
destination.push(e)
}
}
})
} else {
if (target && typeof target === 'object') {
Object.keys(target).forEach((key) => {
destination[key] = target[key]
})
}
Object.keys(src).forEach((key) => {
if (typeof src[key] !== 'object' || !src[key]) {
destination[key] = src[key]
} else {
if (!target[key]) {
destination[key] = src[key]
} else {
destination[key] = merge(target[key], src[key])
}
}
})
}
return destination
}
module.exports = merge