Reputation: 34113
const ingredients = {
fruit: 'orange', liquid: 'water', vegetable: 'tomato', spices: 'curry'
};
I want to pick some of the properties from ingredients
and add them to a new object - shoppingList
.
Right now I'm doing it like this:
const shoppingList = {};
shoppingList.fruit = ingredients[fruit];
shoppingList.spices = ingredients[spices];
Is there any more convenient way of doing the above? I'm envisioning a function of some sort to which I can give ingredients
, fruit
and spices
and it will return a new object with those properties and values.
Upvotes: 1
Views: 64
Reputation: 2437
I'm not going to provide you a function, I just believe this way goes more clean
const ingredients = {
fruit: 'orange',
liquid: 'water',
vegetable: 'tomato',
spices: 'curry'
}
//ingredients, fruit and spices
const {
fruit,
spices
} = ingredients
const newObj = {
fruit,
spices
}
document.write(JSON.stringify(newObj))
Upvotes: 0
Reputation: 469
You could use a function which destructures it the way you like.
function applySpicesandFruit ({ fruit, spices}) {
this.fruit = fruit;
this.spices = spices
return this;
}
applySpicesandFruit.call(shoppinglist, ingredients);
Upvotes: 0
Reputation: 31024
You can use reduce to generate a new object based on keys that you pass to a function.
Small running example:
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);
If you want to go really crazy you can add it to the Object.prototype
and invoke it directly on objects.
Note that this will add the pick
method to all objects, so maybe consider adding it just to some of your objects:
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);
Upvotes: 1