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
/**
* @param { object } obj
* @returns { object }
*/
const deepCopy = (obj) => {
let target = null
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
target = []
obj.forEach(item => {
target.push(deepCopy(item))
})
} else if (obj) {
target = {}
for (const [key, value] of Object.entries(obj)) {
target[key] = deepCopy(obj[key])
}
} else {
target = obj
}
} else {
target = obj
}
return target
}