I'm trying to determine if there is any better/shorter way of taking a subset of the properties on an object and adding (only) those properties to another object. Obviously this isn't the most important thing in the world, but since I do this sort of thing fairly often it would be nice to figure out the ideal pattern for it.
Let's say I have an object, eg.
const cheesyRecipes = {
cheesyBread: ...,
grilledCheeseSandwich: ...,
macAndCheese: ...,
...
}
and I want to apply a subset of that object on to another object, eg.
const cheesyBreadRecipes = {};
// do something with cheesyRecipes?
cheesyBreadRecipes; // == {cheesyBread, grilledCheeseSandwich}
I see a few ways I can do it. I can go the old school way ...
const cheesyRecipesWithBread = [`cheesyBread`, `grilledCheeseSandwhich`];
for(var i = 0; i < cheesyRecipesWithBread.length; i++) {
const recipeName = cheesyRecipesWithBread[i];
cheesyBreadRecipes[recipeName] = cheesyRecipes[recipeName];
});
or I can get a little fancier and use reduce
...
[`cheesyBread`, `grilledCheeseSandwhich`].reduce((memo, recipeName) => {
memo[recipeName] = cheesyRecipes[recipename];
return memo;
}, cheesyBreadRecipes);
or I can get even fancier and halve the line count by using ES6 destructuring ...
const {cheesyBread, grilledCheeseSandwhich} = cheesyRecipes;
Object.apply(cheesyBreadRecipes, {cheesyBread, grilledCheeseSandwhich});
But even that last one, which is clearly the shortest, seems to violate the DRY principle by repeating every recipe's name on both lines. So, my question is, is there any clever way I can use destructuring (or anything else for that matter) to apply a subset of one object's properties on to another, without having to repeat each property twice? Or is my last example as good as it gets?