javascript - Ionic 2 和 JSON 数据添加

标签 javascript json ionic2

我正在使用 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/

相关文章:

javascript - d3 treemap 根据 json 中传递的数据改变颜色

javascript - 一键启动两个 Action ASP.NET

json - 使用重复字段解码 JSON

ios - 更新您的 APNS 证书时发生错误 IOS 通知 Firebase

ionic-framework - 如何禁用或隐藏 Ionic 2 <ion-content> 中的滚动条

javascript - 如何通过字符串访问对象成员?

javascript - jquery 字限制器?

sql - postgres 中的聚合函数中的 DISTINCT ON

javascript - 自动完成 json_encode 按列返回

javascript - 如何使用 TypeScript 获取所选元素的 HTML?