Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 761
Mac Luc Avatar asked Feb 20 '14 23:02

Mac Luc


People also ask

How do I update localStorage values?

Using localStorage object, we will invoke getItem('Key','Value') method to set data using localStorage. setItem('Key','Value') and change the button text using localStorage. getItem('Key').

Can we update localStorage?

LocalStorage can only store strings, which is why you're stringifying your object before storing it. To manipulate the stored string as an object, you can pass it to JSON. parse (assuming it's properly JSON-formatted). Then to store the modified version, you need to convert it back into a string.

How does JSON store data in localStorage in react?

Storing Data to localStorage With the setItem() Method Note: In order to store data in localStorage , we must first convert it to JSON string using the JSON. stringify() function. And when we want to retrieve it, we will parse the data using JSON. parse() , converting the JSON string back to a JSON object.


1 Answers

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
like image 71
epascarello Avatar answered Oct 03 '22 15:10

epascarello