Search code examples
javascriptobjectmergeecmascript-6object-properties

Merge specific prop of objects into one using es6?


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.

Suppose I'm given:

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.


Solution

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

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