使用es6将对象的特定属性合并为一个吗? [英] Merge specific prop of objects into one using es6?

查看:445
本文介绍了使用es6将对象的特定属性合并为一个吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,这是SO中最常见的问题,但是,总而言之,这些问题涉及合并两个完整的对象.

This is by far the most common question asked in SO, however, all in all, the questions asked refers to merging two whole objects.

就我而言,这是完全不同的.

In my case, it's quite different.

假设我得到了

const P1 = {
  "name"          : "Person1",
  "profession"    : "Student",
  "gender"        : "Male",
  "type"          : "Patient",
}

const E1 = {
  "age"           : "30",
  "dob"           : "20/12/1970",
  "address"       : "122 Harrow Street",
  "contactNumber" : "07473033312",
}

并且我想将这两个合并以提供以下内容:

and I want to merge these two to give me the following:

const Result = {
  "name"          : "Person1",
  "type"          : "Patient",
  "age"           : "30",
  "dob"           : "20/12/1970",
}

问题是,我不想合并两个完整的项目.我想合并特定的道具而不循环.

The issue is, I don't want to merge two whole projects. I want to merge specific props without looping.

当前,我们可以使用如下所示的跨距实现合并:

Currently, we can achieve the merge by using the spread like so:

const data = [...P1, ...E1];.

但是这合并了两个,这是我不想要的.

But this merges both, which I don't want.

推荐答案

 const result = (({name, type}, {age, dob}) => ({name, type, age, dob}))(P1, P2);

只需部分破坏P1和P2并建立一个新对象.

Just partially destruct P1 and P2 and build up a new object.

这篇关于使用es6将对象的特定属性合并为一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆