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.
If you're aware of what properties the merged object should have (in your case
name, type, age, dob
)How about defining them like so:
Since you're looking for an ES6 way, I'd say using deconstruction is the way to go:
You could use a complete dynamic approach by using an array for the wanted properties and another for the objects.
Then build a new object out of the found objects.
Just partially destruct P1 and P2 and build up a new object.
I guess your best bet is to unpack and then pack it again:
This is silly, but that's all we've got in ES6.
An alternative would be a function like lodash's
_.pick
.If you have an array of source objects, replace
{...P1, ...E1}
with spreadedObject.assign
: