You need to deserialize, modify, and re-save the item.
Remember that localStorage
is a simple key/value store for strings
: it does not provide any way to manipulate the contents of those stored strings (you don't even need to store JSON, you could store YAML, XML, or Base64-encoded arbitrary binary data in localStorage
.
Like so:
function storeCart( cart ) {
localStorage.setItem( 'cart', JSON.stringify( cart ) );
}
/** Returns 'true' if the specified key/value was removed from the stored cart object - otherwise 'false'. */
function deleteItemFromStoredCart( key ) {
const cartString = localStorage.getItem( 'cart' );
if( !cartString ) return false;
try {
const cart = JSON.parse( cartString );
if( !( key in cart ) ) return false;
delete cart[ key ];
storeCart( cart );
return true;
}
catch( err ) {
console.log( "Error: ", err );
return false;
}
}