Reputation: 5444
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
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
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
Reputation: 114461
There are two options:
getItem
, then push/set the new element, then use setItem
.localStorage.setItem('obj:' + x.time, x)
) and the use for (x in localStorage) {...}
to find all the keys.Upvotes: 4
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