javascript 在本地存储中追加对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19902670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:11:34  来源:igfitidea点击:

Append objects in local storage

javascriptlocal-storage

提问by Jose Ramon

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?

我想每隔一秒添加 obj 的多个实例,并给出一个时间键。如何附加 obj 而不是每次都更改它?

回答by Prateek

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.

您可能还需要考虑使用对象而不是数组并使用产品名称作为键。这将防止在 LocalStorage 中出现重复的条目。

回答by 6502

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.
  1. 而不是存储对象存储对象的列表/映射,然后添加元素只需先执行getItem,然后推送/设置新元素,然后使用setItem.
  2. 使用日期作为键(例如localStorage.setItem('obj:' + x.time, x))存储对象并使用for (x in localStorage) {...}查找所有键。

回答by dheerendra

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

回答by Sirko

Basically you have to retrieve the object, add your value and then write it back to localStorage.

基本上,您必须检索对象,添加您的值,然后将其写回localStorage.

var obj = JSON.parse( localStorage.getItem('obj') ) || {};
obj[ timestamp ] = 'newvalue';
localStorage.setItem('obj', JSON.stringify(obj));