我正在使用 Ionic 2 Storage 来保存表单数据。我这样保存数据:
this.storage.set(key, JSON.stringify(formData));
我检索并尝试更新数据,如下所示:
this.getReport(key).then((report) => {
var objReport = JSON.parse(report);
objReport.push(data); //this is the problem
this.storage.set(pk, JSON.stringify(objReport));
});
getReport 就是这样:
getReport(key) {
return this.storage.get(key);
}
所以我知道 .push 适用于数组而不是对象,但我认为执行所有这些转换效率不高,因为我正在处理大型对象。
我的问题是:从存储中检索 json 并将其附加到其中的最有效方法是什么?如果对象没有像数组这样的 push 方法,那么 .parse 返回一个对象对我来说是没有意义的。
这是错误:
Runtime Error Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined
最佳答案
这个错误的意思是,目前没有该键的记录。 因此,您必须进行如下检查:
this.getReport(key).then((report) => {
var objReport = [];//initialise empty Array
if(report){ //if there is a record in that key location
objReport = JSON.parse(report); //parse the record & overwrite objReport
}
objReport.push(data); //Now this push will happen regardless of report or not
this.storage.set(pk, JSON.stringify(objReport));
});
关于javascript - Ionic 2 和 JSON 数据添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689516/