javascriptobjectecmascript-6spread-syntaxobject-properties

merge props from nested objects as one single object using es6


Suppose we are given the following:

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": {...}
  }
}

How can we merge the two objects (Patients & Doctors) as One object so that the result is as follows:

const Result = {
  "name": "Doctor1",
  "profession": "Dr",
  "Patients": {...},
  P1: {
    "Doctors": {...}
  },
  P2: {
    "Doctors": {...}
  }
}

As far as I know, I could use destruct on both objects to partially destruct and form a new object. But this makes it harder to obtain the nested object (i.e. "Doctors": {...} within P1 and P2.

For example:

let result = (({
      name,
      profession,
      Patients
    }, { /* Im not sue what to do here */ }) => ({
      Patients,
      /* Im not sue what to do here */ ))(Doctor, Object.values(Patients));


Solution

  • Use spread syntax ... and reduce function.

    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
    }