在localStorage中向对象添加对象

时间:2013-10-28 12:41:10

标签: javascript local-storage

好的,我已经尝试过这里的示例了,我知道可能有一些不同的方法在localstorage中向数组添加对象而不是覆盖它但是我没有找到至少其中一个。

获得此代码将对象存储在数组中,但它会覆盖自身。愿有人告诉我我错过了什么吗? (而且我担心我可能会失踪很多)。

function addEntry() {
    var entryTitle = document.getElementById("entryTitle").value;
    var entryText = document.getElementById("entryText").value;
    var entry = {
        "title": entryTitle,
        "text": entryText
    };
    localStorage.setItem("entry", JSON.stringify(entry));
    var allEntries = [];
    allEntries.push(entry);
    localStorage.setItem("allEntries", JSON.stringify(allEntries));
};

5 个答案:

答案 0 :(得分:25)

使用setItem时,它会覆盖之前的项目。您需要使用getItem检索旧列表,附加到它,然后将其保存回localStorage:

function addEntry() {
    // Parse any JSON previously stored in allEntries
    var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
    if(existingEntries == null) existingEntries = [];
    var entryTitle = document.getElementById("entryTitle").value;
    var entryText = document.getElementById("entryText").value;
    var entry = {
        "title": entryTitle,
        "text": entryText
    };
    localStorage.setItem("entry", JSON.stringify(entry));
    // Save allEntries back to local storage
    existingEntries.push(entry);
    localStorage.setItem("allEntries", JSON.stringify(existingEntries));
};

以下是展示上述内容的fiddle

答案 1 :(得分:8)

也许您只需要在推送新条目之前获取条目:

var allEntries = JSON.parse(localStorage.getItem("allEntries")) || [];
allEntries.push(entry); 
//etc...

答案 2 :(得分:0)

const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
arr.push(object);
localstorage.setitem(json.strigify('key_name', arr);

答案 3 :(得分:0)

HTML5 localStorage允许您存储键/值对数据。 键和值都必须是字符串。要将数组存储为键或值,您需要将数组编码为JSON字符串。并且在检索时,您需要将其解码回数组。

const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
const data = [arr, ...[object]];
localstorage.setitem(json.strigify('key', data);

答案 4 :(得分:0)

将对象添加到localStorage(Ionic)中的阵列:

var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var testObject ={username:this.username, 
mobile:this.mobile,
email:this.email,
type:this.type,
password:this.password};

localStorage.setItem('testObject', JSON.stringify(testObject));
existingEntries.push(testObject);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
相关问题