Get specific item inside an object


#1

For example, I want to get the calories of Recipenum : r5, how can i do that in an object and store it to localstorage?

{
“Recipenum” : “r1”,
“FoodName” : “Fish Cardillo”,
“Calories” : “170”,
“Fat” : “4g”,
“Protein” : “20g”,
“Carbs” :“13g”
},{
“Recipenum” : “r2”,
“FoodName” : “Fish Cardillo2”,
“Calories” : “180”,
“Fat” : “4g”,
“Protein” : “20g”,
“Carbs” :“13g”
}
}

Any help will be much appreciated.


#2

loop over the array --> if you have found it --> break the loop:

var i = 0,
     item;
for (i; i < items.length; i = i + 1) {
  if (items[i].Recipenum === 'r5') {
    item = items[i];
    break;
  }
}

if (item) {
  // get item data like item.Fat, item.Carbs .... 
}

#3

I am using ngStorage plugin which allows storing objects directly in localstorage in object form itself.
like if your above object is called Recipes= []… then

$localStorage.Recipes = Recipes;

// then acces items as...

$localStorage.Recipes[index].Calories= 'yourValue';

In your case, index you want is r5's calorie

$localStorage.Recipes[r5's index].Calories= 'yourValue';