1

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

4

1 回答 1

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
}

于 2018-02-14T22:38:46.697 回答