Jose Ramon
Jose Ramon

Reputation: 5444

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?

Upvotes: 10

Views: 23873

Answers (4)

Sirko
Sirko

Reputation: 74036

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));

Upvotes: 8

dheerendra
dheerendra

Reputation: 537

function store() 
{
    var person=new Object();
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    person.firstname="John";
    person.lastname="Doe";
    person.age=50;
    person.eyecolor="blue";
    localStorage.setObj("temp", person);
    var obj=localStorage.getObj("temp");
    for(var i in obj)
    alert(i+"--"+obj[i]);
}
Storage.prototype.setObj = function(key, obj) {
     return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
     return JSON.parse(this.getItem(key))
}

Upvotes: 3

6502
6502

Reputation: 114461

There are two options:

  1. Instead of storing the object store a list/map of objects, then to add an element just first do the getItem, then push/set the new element, then use setItem.
  2. Store the objects using the date as the key (e.g. localStorage.setItem('obj:' + x.time, x)) and the use for (x in localStorage) {...} to find all the keys.

Upvotes: 4

Prateek
Prateek

Reputation: 6965

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.

Upvotes: 21

Related Questions