将对象添加到本地存储中的数组

adding objects to array in localStorage

本文关键字:存储 数组 对象 添加      更新时间:2023-09-26

好的,我尝试在这里遵循示例,我知道可能有几种不同的方法可以将对象添加到本地存储中的数组中而不覆盖它,但我找不到其中的至少一种。

让此代码将对象存储在数组中,但它会覆盖自己。谁能告诉我我错过了什么?(恐怕我可能会错过很多)。

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

当你使用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));
};

这是一个小提琴,它演示了上述内容。

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

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

将对象添加到 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));

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

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.stringify('key', data);