const ingredients = {
fruit: 'orange', liquid: 'water', vegetable: 'tomato', spices: 'curry'
};
我想从 ingredients
中挑选一些属性并将它们添加到一个新对象 - shoppingList
。
现在我是这样做的:
const shoppingList = {};
shoppingList.fruit = ingredients[fruit];
shoppingList.spices = ingredients[spices];
有没有更方便的方法来完成上述操作?我正在设想某种类型的函数,我可以为其提供 ingredients
、fruit
和 spices
,它将返回具有这些属性的新对象和值(value)观。
最佳答案
您可以使用 reduce根据传递给函数的键生成新对象。
小运行示例:
const ingredients = {
fruit: 'orange',
liquid: 'water',
vegetable: 'tomato',
spices: 'curry'
};
function pick(keys, obj) {
const newObj = keys.reduce((result, currentKey) => {
result[currentKey] = obj[currentKey];
return result;
}, {});
return newObj;
}
const myKeys = ['fruit', 'spices'];
const customObj = pick(myKeys, ingredients);
console.log(customObj);
如果你真的想疯狂,你可以将它添加到 Object.prototype
并直接在对象上调用它。
请注意,这会将 pick
方法添加到所有对象,因此可以考虑将它仅添加到您的某些对象:
const ingredients = {
fruit: 'orange',
liquid: 'water',
vegetable: 'tomato',
spices: 'curry'
};
Object.prototype.pick = function(keys){
const newObj = keys.reduce((result, currentKey) => {
result[currentKey] = this[currentKey];
return result;
}, {});
return newObj;
}
const myKeys = ['fruit', 'spices'];
const customObj = ingredients.pick(myKeys);
console.log(customObj);
关于javascript - 使用来自其他对象的属性值对创建一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029638/