mercredi 4 mars 2015

Storing extra data about an object

I want to store some extra data about an object (in this case, a recipe) without storing it in the object itself. What is the best way of doing this?


Here is a simple example. Am I doing something wrong architecturally?



var recipes = {
scones: {egg:2, milk: 5},
pancakes: {eggs:3, milk: 2}
}

var recipesCooked = {
scones: 0,
pancakes: 0
}

function makeRecipe(recipe){

// I don't want to have to do this loop every time.
// Is there a better way of storing this data??
for(var key in recipes) {
if(recipes.hasOwnProperty(key) && recipes[key] === recipe){
recipesCooked[key]++;
}
}
//...snipped...make the recipe
}

makeRecipe(recipes.pancakes);
//recipesCooked.pancakes should be 1


In other words: I need some way of tying the extra data (recipesCooked) to the correct recipe, and the only way I know of doing that is by using the same key. But this seems bad, especially because I have to iterate back through the recipes to find the name of the key.


Aucun commentaire:

Enregistrer un commentaire