【发布时间】:2021-04-29 07:21:14
【问题描述】:
我正在尝试从本地存储中检索一个数组,使用相同的键附加一个新数组,然后将其放回存储中。但是我似乎无法让它工作,我尝试将我的数组变成对象,将对象变成数组(我是编程新手,所以我不确定最好的方法是什么。)我也尝试使用扩展运算符、object.entries()、object.assign() 和其他一些无意义的选项。
编辑:
保存到存储的是用户输入值:
"[[["name","bob ross"],["about","Painter"]]]"
我希望用户能够为 name 添加“Bilbo Baggins”,为 about 添加“Hobbit”,那么存储应该如下所示:
"[[["name","bob ross"],["about","Painter"]]], [[["name","Bilbo Baggins"],["about","Hobbit"]]]"
任何帮助将不胜感激!这是我的代码:
//============= Allows writing to LocalStorage without overwrite ==========================
submitbtn.addEventListener('click', function () {
const oldInfo = JSON.parse(localStorage.getItem('data')); // Retrieves info from storage to make it writeable
console.log('old Info: ', oldInfo); // Shows user what's currently saved in oldInfo
const newInfo = {};
newInfo.name = name.value; // Name and about are user input values
newInfo.about = about.value;
let array = Object.entries(newInfo); // Turns newInfo into an array
console.log('new info: ', newInfo);
oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log(oldInfo);
localStorage.setItem('data', JSON.stringify(oldInfo)); // Saves newly updated array to localStorage
});
【问题讨论】:
-
不清楚您期望发生什么,究竟是什么?您能否在您的问题中添加一个示例,包括之前的存储状态、新信息是什么以及之后您期望存储中的内容? (所以,只是简单的数据,你需要做什么?)
-
在问题中,@TraktorJack。
-
感谢您清理它
-
没问题。嗯,据我所知,您的代码应该完全执行您想要的操作...您是否收到任何控制台错误?
-
不,只是没有附加新值。它只是覆盖它们
标签: javascript arrays json object