Mac Luc
Mac Luc

Reputation: 1001

How to update json value in localstorage

So I have an array stringify'ed and saved in my localStorage under 'persons' key.

arr = [{"name":"a", "age": 1, "sport":"football"},
{"name":"b", "age": 2, "sport":"volley"},
{"name":"c", "age": 3, "sport":"basket"}];
localStorage.setItem('persons', JSON.stringify(arr));

When I need to update age for person with name x (lets say the input is person with name b), my approach is to get and parse my localStorage key:

var persons = JSON.parse(localStorage.persons);

Then I make a for loop to loop through the objects and find object with name b:

for (var i = 0; i < persons.length; i++) {
   if(inputName === persons[i].name){
       persons[i].age += 2
       localStorage.setItem("persons", JSON.stringify(aCustomers[i].age));
   }
}

This doesnt seem to work. I've found my match in the loop, but I dont know how to add 2 years to the age and update that value in my localStorage.persons without overwriting and destroying the json objects.

Upvotes: 20

Views: 54137

Answers (1)

epascarello
epascarello

Reputation: 207501

You need to set the object back again like you did originally, right now you are storing only a number, not the object.

var persons = JSON.parse(localStorage.persons);
for (var i = 0; i < persons.length; i++) {
   if(inputName === persons[i].name){  //look for match with name
       persons[i].age += 2;  //add two
       break;  //exit loop since you found the person
   }
}
localStorage.setItem("persons", JSON.stringify(persons));  //put the object back

Upvotes: 43

Related Questions