Object.assign() 함수는 요소를 위로부터 아래 방향으로 복사하기 때문에 깊은복사가 안된다.
깊은복사 assignDeep
Object.assignDeep(target, source[, source2, source3, …])
[code]
Object.assignDeep = (target, …sources) => {
const isObject = (item) => {
return item && typeof item === ‘object’ && !Array.isArray(item)
}
if (!sources.length) return target
const source = sources.shift()
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} })
if (isObject(target[key])) Object.assignDeep(target[key], source[key])
else target[key] = source[key]
} else if (Array.isArray(source[key])) {
if (!Array.isArray(target[key])) target[key] = []
for (const k in source[key]) {
target[key].push(source[key][k])
}
} else {
Object.assign(target, { [key]: source[key] })
}
}
return Object.assignDeep(target, …sources)
}
[/code]
사용예제
[code]
const objA = {
human: {
assets: [“food”],
child: [
{
name: “천재”,
},
],
},
};
const objB = {
human: {
name: “명박”,
age: 80,
addr: “감옥”,
assets: [“car”, “house”, “finance”],
child: [
{
name: “바보”,
},
],
},
};
const objC = {
animal: {
name: “명박”,
age: 2,
addr: “너거집”,
child: [
{
name: “순이”,
},
{
name: “명이”,
},
{
name: “똘이”,
},
],
},
};
const a = Object.assignDeep({}, objA, objB, objC);
console.log(a);
[/code]
실행결과
[code]
{
human: {
assets: [
‘food’,
‘car’,
‘house’,
‘finance’
],
child: [
{
name: ‘천재’
},
{
name: ‘바보’
}
],
name: ‘완용’,
age: 80,
addr: ‘감옥’
},
animal: {
name: ‘꽁이’,
age: 2,
addr: ‘너거집’,
child: [
{
name: ‘순이’
},
{
name: ‘명이’
},
{
name: ‘똘이’
}
]
}
}
[/code]