Closed. This question needs to be more focused。它当前不接受答案。
想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
上个月关闭。
如何从对象集合中返回密钥并通过配方进行计算?我陷入了一个for循环,并已经使用.reduce()进行了尝试。但是我还不太了解。有人可以帮我或向我解释吗?解决此问题的最佳方法是什么?
想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
上个月关闭。
如何从对象集合中返回密钥并通过配方进行计算?我陷入了一个for循环,并已经使用.reduce()进行了尝试。但是我还不太了解。有人可以帮我或向我解释吗?解决此问题的最佳方法是什么?
var soup = {
potato: 3,
onion: 1,
corn: 5
};
var gratin = {
meat: 2,
onion: 2,
pea: 5
};
var pizza = {
cheese: 1,
tomato: 3,
oregano: 2
};
var edoka = { // in a store, the values are the prices per ingredient
cheese: 8,
corn: 3,
meat: 6,
onion: 4,
pea: 1,
oregano: 7,
potato: 5,
tomato: 6
};
var were = {
cheese: 6,
corn: 2,
meat: 9,
onion: 5,
pea: 2,
oregano: 6,
potato: 3,
tomato: 3
};
var brutto = {
cheese: 6,
corn: 2,
meat: 9,
onion: 5,
pea: 2,
oregano: 8,
potato: 3,
tomato: 4
};
var allStores = { // this is an example of a "storeCollection"
Brutto: brutto,
Edoka: edoka,
Were: were,
};
function cheapestStoreForRecipe(recipe, storeCollection){
// make it return the key for the store in storeCollection
// that has the cheapest total cost for recipe. Feel free
// to use costOfRecipe inside this function!
}
最佳答案
您可以使用Object.keys()
和reduce
:
var soup = { potato:3, onion:1, corn:5 },
gratin = { meat:2, onion:2, pea:5 },
pizza = { cheese:1, tomato:3, oregano:2 };
var edoka = { cheese:8, corn:3, meat:6, onion:4, pea:1, oregano:7, potato:5, tomato:6 },
were = { cheese:6, corn:2, meat:9, onion:5, pea:2, oregano:6, potato:3, tomato:3 },
brutto = { cheese:6, corn:2, meat:9, onion:5, pea:2, oregano:8, potato:3, tomato:4 };
var allStores = {
Brutto: brutto,
Edoka: edoka,
Were: were,
};
function cheapestStoreForRecipe(recipe, storeCollection) {
var cheapest = Object.keys(storeCollection).reduce((result, name) => {
var total = getStoreRecipePrice(storeCollection[name], recipe);
if (result === null || total < result.total) {
return {name, total};
}
return result;
}, null);
return cheapest;
}
function getStoreRecipePrice(store, recipe) {
// price * quantity
return Object.keys(recipe).reduce((total, key) => total + store[key] * recipe[key], 0);
}
console.log('soup: ', cheapestStoreForRecipe(soup, allStores));
console.log('gratin: ', cheapestStoreForRecipe(gratin, allStores));
console.log('pizza: ', cheapestStoreForRecipe(pizza, allStores));
关于javascript - 如何从存储在数组中的对象返回键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60682789/
10-11 11:59