Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append objects in local storage

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?

like image 955
Jose Ramon Avatar asked Nov 11 '13 09:11

Jose Ramon


People also ask

Can I add object in localStorage?

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.

How do I store multiple items in localStorage?

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").

Can you store an array of objects in localStorage?

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 .


2 Answers

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.

like image 194
Prateek Avatar answered Sep 30 '22 01:09

Prateek


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));
like image 26
Sirko Avatar answered Sep 30 '22 01:09

Sirko