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.
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').
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With