使用 es6 将嵌套对象中的 props 合并为一个对象
merge props from nested objects as one single object using es6
假设我们有以下内容:
const Patients = {
P1: {
"name": "Person1",
"profession": "Student",
"gender": "Male",
"type": "Patient",
"Doctors": {...}
},
P2: {
"name": "Person2",
"profession": "Student",
"gender": "Male",
"type": "Patient",
"Doctors": {...}
}
}
const Doctors = {
D1: {
"name": "Doctor1",
"profession": "Dr",
"gender": "Male",
"type": "Doctor",
"Patients": {...}
}
}
我们如何将两个对象(患者和医生)合并为一个对象,以便结果如下:
const Result = {
"name": "Doctor1",
"profession": "Dr",
"Patients": {...},
P1: {
"Doctors": {...}
},
P2: {
"Doctors": {...}
}
}
据我所知,我可以对两个对象使用 destruct 来部分破坏并形成一个新对象。但这使得获取嵌套对象变得更加困难(即 P1 和 P2 中的 "Doctors": {...}
。
例如:
let result = (({
name,
profession,
Patients
}, { /* Im not sue what to do here */ }) => ({
Patients,
/* Im not sue what to do here */ ))(Doctor, Object.values(Patients));
使用扩展语法 ...
和 reduce
函数。
const Patients = { P1: { "name": "Person1", "profession": "Student", "gender": "Male", "type": "Patient", "Doctors": {} }, P2: { "name": "Person2", "profession": "Student", "gender": "Male", "type": "Patient", "Doctors": {} }}
const Doctors = { D1: { "name": "Doctor1", "profession": "Dr", "gender": "Male", "type": "Doctor", "Patients": {} }}
var result = { ...Doctors.D1,
...Object.keys(Patients).reduce((a, k) => {
a[k] = {
"Doctors": Patients[k].Doctors
};
return a;
}, {})
};
delete result.gender;
delete result.type;
console.log(result);
.as-console-wrapper {
max-height: 100% !important
}
假设我们有以下内容:
const Patients = {
P1: {
"name": "Person1",
"profession": "Student",
"gender": "Male",
"type": "Patient",
"Doctors": {...}
},
P2: {
"name": "Person2",
"profession": "Student",
"gender": "Male",
"type": "Patient",
"Doctors": {...}
}
}
const Doctors = {
D1: {
"name": "Doctor1",
"profession": "Dr",
"gender": "Male",
"type": "Doctor",
"Patients": {...}
}
}
我们如何将两个对象(患者和医生)合并为一个对象,以便结果如下:
const Result = {
"name": "Doctor1",
"profession": "Dr",
"Patients": {...},
P1: {
"Doctors": {...}
},
P2: {
"Doctors": {...}
}
}
据我所知,我可以对两个对象使用 destruct 来部分破坏并形成一个新对象。但这使得获取嵌套对象变得更加困难(即 P1 和 P2 中的 "Doctors": {...}
。
例如:
let result = (({
name,
profession,
Patients
}, { /* Im not sue what to do here */ }) => ({
Patients,
/* Im not sue what to do here */ ))(Doctor, Object.values(Patients));
使用扩展语法 ...
和 reduce
函数。
const Patients = { P1: { "name": "Person1", "profession": "Student", "gender": "Male", "type": "Patient", "Doctors": {} }, P2: { "name": "Person2", "profession": "Student", "gender": "Male", "type": "Patient", "Doctors": {} }}
const Doctors = { D1: { "name": "Doctor1", "profession": "Dr", "gender": "Male", "type": "Doctor", "Patients": {} }}
var result = { ...Doctors.D1,
...Object.keys(Patients).reduce((a, k) => {
a[k] = {
"Doctors": Patients[k].Doctors
};
return a;
}, {})
};
delete result.gender;
delete result.type;
console.log(result);
.as-console-wrapper {
max-height: 100% !important
}