我想确定是否有任何更好/更短的方式获取对象的属性的子集,并将这些属性添加(仅)到另一个对象。很明显,这不是世界上最重要的事情,但是因为我经常这样做,所以找出理想的模式是很好的。是否有更好/更短的模式来设置另一个对象的对象属性的子集?
比方说,我有一个对象,例如。
const cheesyRecipes = {
cheesyBread: ...,
grilledCheeseSandwich: ...,
macAndCheese: ...,
...
}
,我想申请到另一个物体,例如该对象的一个子集。
const cheesyBreadRecipes = {};
// do something with cheesyRecipes?
cheesyBreadRecipes; // == {cheesyBread, grilledCheeseSandwich}
我看到几种方法可以做到。我可以去老派的方式...
const cheesyRecipesWithBread = [`cheesyBread`, `grilledCheeseSandwhich`];
for(var i = 0; i < cheesyRecipesWithBread.length; i++) {
const recipeName = cheesyRecipesWithBread[i];
cheesyBreadRecipes[recipeName] = cheesyRecipes[recipeName];
});
或者我可以得到一个小票友和使用reduce
...
[`cheesyBread`, `grilledCheeseSandwhich`].reduce((memo, recipeName) => {
memo[recipeName] = cheesyRecipes[recipename];
return memo;
}, cheesyBreadRecipes);
或者我可以得到更炫,并通过使用减半行数ES6解构......
const {cheesyBread, grilledCheeseSandwhich} = cheesyRecipes;
Object.apply(cheesyBreadRecipes, {cheesyBread, grilledCheeseSandwhich});
但是,即便是最后一个,这显然是最短的,似乎是由两条线重复的每一节的名称违反了DRY原则。所以,我的问题是,有没有什么聪明的方法可以使用解构(或其他任何事情)来将一个对象的属性的子集应用到另一个,而不必重复每个属性两次?或者,我的最后一个例子和它一样好?
不是100%肯定,如果这正是你所追求的,但你可能看看http://stackoverflow.com/q/25553910/3123195 –
良好的渔获:这个问题似乎与这个问题一样(他们似乎也得出了与此相同的结论)。我会把我的标记作为重复,谢谢! – machineghost