I store objects in local storage with the following:
localStorage.setItem('obj', JSON.stringify(obj));
I want to add multiple instances of obj every one second, giving a time key. How can I append obj instead of change it every time?
We can store more user information in a single key this way. In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON.
You can store the value in localStorage with the key value pair. It has two methods setItem(key, value) to store the value in the storage object and getItem(key) to retrieve the value from the storage object. document. getElementById("result").
The localStorage API in browsers only supports adding information in a key:pair format and the key and the pair should be of type string thus native objects or arrays cannot be stored in the localStorage .
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem =
{
'product-name': itemContainer.find('h2.product-name a').text(),
'product-image': itemContainer.find('div.product-image img').attr('src'),
'product-price': itemContainer.find('span.product-price').text()
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in LocalStorage.
Basically you have to retrieve the object, add your value and then write it back to localStorage
.
var obj = JSON.parse( localStorage.getItem('obj') ) || {};
obj[ timestamp ] = 'newvalue';
localStorage.setItem('obj', JSON.stringify(obj));
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