使用es6将嵌套对象中的props合并为一个单个对象

时间:2018-02-14 22:22:35

标签: javascript object ecmascript-6 spread-syntax object-properties

假设我们得到以下内容:



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));




1 个答案:

答案 0 :(得分:2)

使用扩展语法...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
}