질문
나는 두 개의 동일한 물건을 가지고 있습니다.
let a = {
title : "developer”,
startDate:{ month :’jan’}
}
let b = {
title :{
value: ""
} ,
startDate :{month:{value:””}}
}
다음과 같은 객체를 얻으려면이 두 가지를 동적으로 병합해야합니다.
let c = {
title :{
value: "developer"
} ,
startDate:{
month:{ value:” jan”}}
}
답변1
객체 b
는 추가 'value'속성이있는 객체 a
의 복제본 일 뿐이므로 필요하지 않습니다.
전체 a
객체를 탐색 한 다음 b
객체의 값을 전체 복사 할 수 있습니다.
객체의 마지막 레벨로 이동하고 다른 객체의 값을 복사 할 수있는 재귀 메서드를 작성했습니다.
function mergeObj(sourceObj, newObj) {
Object.keys(sourceObj).forEach(key => {
if (sourceObj[key] && typeof sourceObj[key] === 'object') {
newObj[key] = {};
mergeObj(sourceObj[key], newObj[key]);
} else {
// updating properties
newObj[key] = {};
newObj[key]['value'] = sourceObj[key];
}
});
}
let a = {
title : "developer",
startDate:{ month :'jan'}
};
let b = {};
mergeObj(a,b);
console.log(b);
답변2
두 객체가 동일한 구조를 갖도록 만든 다음 깊은 병합을 실행해야 할 수 있습니다. lodash의 병합 이 도움이 될 수 있습니다.
const newA = Object.entries(a).reduce((newObject, [key, value]) => ({
...newObject,
[key]: { value },
}, {}))
// newA looks now like
//
// {
// title: {
// value: "developer
// }
// }
let c = _.merge(a, b); // lodash merge for deep merge. Otherwise write your own
답변3
문제에 대한 해결 방법은 다음과 같습니다.
let a = {
title : "developer",
startDate:{ month :'jan'}
}
let b = {
title :{
value: ''
} ,
startDate :{month:{value:''}}
}
var c = {};
c.startDate = {};
c.title = {};
c.startDate.month = {};
c.startDate.month.value = a.startDate.month;
c.title.value = a.title;
console.log("Merged object",c);
답변4
이 작업을 수행하는 함수를 구현할 수 있습니다. 예를 들어 :
let a = {
title: "developer",
startDate: { month: "jan" }
};
let b = {
title: {
value: ""
},
startDate: { month: { value: "" }}
};
이것을 사용하여 값을 가져올 수 있습니다.
const mergeObject = (a, b) => {
b.title.value = a.title;
b.startDate.month.value = a.startDate.month;
return b;
};
지금 호출하면 let c = mergeObject (a, b)
c가
let c = {
title: {
value: "developer"
},
startDate: {
month: { value: "jan" }}
}
물론이 기능은 정확한 요구 사항을 반영하도록 수정할 수 있습니다.
출처 : https://stackoverflow.com/questions/62939656/how-to-merge-two-two-objects-with-different-depths-dynamically