【问题标题】:merge props from nested objects as one single object using es6使用 es6 将嵌套对象中的道具合并为一个对象
【发布时间】:2018-07-25 14:49:13
【问题描述】:

假设我们得到以下内容:

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

我们如何将两个对象(Patients & Doctors)合并为一个对象,结果如下:

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

【问题讨论】:

  • 你不是问this question吗?
  • 是的,我做了,但我改变了我之前的问题,但大多数人说要问一个新问题。请检查上一个问题的 cmets。基本上,现在的区别是我们必须照顾嵌套对象的道具@Icepickle
  • 我看不出合并对您有什么好处,您似乎想在患者和医生之间创建一个链接结构?
  • 所以我面临的问题是,实际上这些对象中的每一个都非常巨大,我不想传递所有东西。我只想要两个对象的一些道具并使用它。 @Icepickle
  • 我不明白这个问题。您不必对那些嵌套对象做任何事情,是吗?由于{...} 省略号和缺少逗号,您的输入和输出有点混乱。

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


【解决方案1】:

使用扩展语法...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-07-25
    • 2021-07-07
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多