You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ES6合并Patients与Doctors对象为单个对象?嵌套解构存难点

嗨,我来帮你搞定这个对象合并的问题!

合并Patients与Doctors对象的解决方案

首先,我先假设你的Patients和Doctors对象大概长这样(方便演示):

const Patients = {
  P1: {
    name: "Alice",
    age: 30,
    Doctors: {
      primary: "Dr. Smith",
      specialist: "Dr. Lee"
    }
  },
  P2: {
    name: "Bob",
    age: 45,
    Doctors: {
      primary: "Dr. Johnson"
    }
  }
};

const Doctors = {
  "Dr. Smith": { department: "General Medicine", yearsExp: 15 },
  "Dr. Lee": { department: "Cardiology", yearsExp: 20 },
  "Dr. Johnson": { department: "Pediatrics", yearsExp: 10 }
};

方法一:解构嵌套对象+展开运算符批量合并

如果你想把每个Patient的关联医生信息,和全局Doctors的详情合并成单个对象,可以这样操作:

const mergedPatients = {};

// 遍历所有Patient
for (const [patientId, patient] of Object.entries(Patients)) {
  // 解构出Patient里的嵌套Doctors对象,同时保留其他基础信息
  const { Doctors: patientDoctors, ...basicPatientInfo } = patient;
  
  // 把每个关联医生的详情合并进来
  const detailedDoctors = Object.fromEntries(
    Object.entries(patientDoctors).map(([role, doctorName]) => [
      role,
      { name: doctorName, ...Doctors[doctorName] }
    ])
  );
  
  // 组装最终的单个Patient对象
  mergedPatients[patientId] = {
    ...basicPatientInfo,
    Doctors: detailedDoctors
  };
}

console.log(mergedPatients);

方法二:直接深层解构获取单个Patient的嵌套Doctors

如果只是单独提取P1或P2里的嵌套Doctors对象,直接用深层解构就搞定了:

// 获取P1的Doctors
const { P1: { Doctors: p1Doctors } } = Patients;
console.log(p1Doctors); // 输出 { primary: "Dr. Smith", specialist: "Dr. Lee" }

// 获取P2的Doctors
const { P2: { Doctors: p2Doctors } } = Patients;
console.log(p2Doctors); // 输出 { primary: "Dr. Johnson" }

关键注意点

  • 处理嵌套对象时,深层解构是核心,比如{ P1: { Doctors } }就能直接跳过外层,拿到P1内部的Doctors对象。
  • 合并对象属性时,**展开运算符(...)**是最简洁的方式,比Object.assign()可读性更强。
  • 批量处理多个对象时,Object.entries()能帮你同时拿到对象的键和值,遍历起来更顺手。

内容的提问来源于stack exchange,提问作者Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:12:16