This is reminiscent of the query you posed yesterday, with the same principles in play.
- Retrieve the most recent value from local storage by using
localStorage.getItem
- Implement your desired changes, whether it involves adding a new item, removing an existing one, or modifying an existing entry—it doesn't make much difference.
- Save the modifications back by utilizing
localStorage.setItem
Check out the provided example below; feel free to experiment here
It demonstrates adding, deleting, and altering existing entries.
// Setting up local storage for this demonstration:
localStorage.setItem("user_login_users", JSON.stringify([{
name: "Elena",
surname: "Rondina"
}, {
name: "Lars",
surname: "Codemonkey"
}]));
// Adding a new user
// Retrieve the user_login_users data from local storage
var usersInLocalStorageAdd = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("before addition:", usersInLocalStorageAdd)
// Add the new user to the object
usersInLocalStorageAdd.push({
name: "Jacky",
surname: "Chan"
});
// Save the change to local storage
localStorage.setItem("user_login_users", JSON.stringify(usersInLocalStorageAdd));
// The new user has now been saved
// The user at the specified position has been deleted:
var afterAdd = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("after addition:", afterAdd)
// Deleting an entry:
// Retrieve the user_login_users data from local storage
var usersInLocalStorageDelete = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("before deletion:", usersInLocalStorageDelete)
// Remove a single user from local storage at the indicated position:
var pos = 0;
if (usersInLocalStorageDelete.length > pos + 1) {
usersInLocalStorageDelete.splice(pos, 1);
localStorage.setItem("user_login_users", JSON.stringify(usersInLocalStorageDelete));
// The user at the given position has been deleted:
var afterDelete = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("after deletion:", afterDelete)
}
// Modifying an existing user:
// Retrieve the data from local storage once more
var usersInLocalStorageForModification = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log('before modification', usersInLocalStorageForModification)
// Define the values we wish to apply
var firstName = {
value: "John"
};
var lastName = {
value: "Smith"
};
// Since pos is still zero, we will alter the first entry.
usersInLocalStorageForModification[pos].name = firstName.value;
usersInLocalStorageForModification[pos].surname = lastName.value;
// The entry has now been modified. We must save it again to retain these changes.
localStorage.setItem("user_login_users", JSON.stringify(usersInLocalStorageForModification));
// The user at the specified position has been modified:
var afterModify = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("after modification:", afterModify)