Adding JSON data to Ionic 2

I've been utilizing Ionic 2 Storage to store form data persistently. The method I use for saving the data is as follows:

this.storage.set(key, JSON.stringify(formData));

When it comes to retrieving and updating the stored data, here's what I do:

this.getReport(key).then((report) => {
  var objReport = JSON.parse(report);
  objReport.push(data); //this is where the issue arises
  this.storage.set(pk, JSON.stringify(objReport));
});

The getReport function looks like this:

getReport(key) {
  return this.storage.get(key);
}

Although I'm aware that .push is meant for arrays and not objects, constantly converting between them isn't ideal due to the size of the objects I'm working with.

So my question is: What would be the most efficient approach to retrieve JSON from storage and append to it? It seems illogical to me that .parse returns an object when objects lack a push method similar to arrays.

Here's the error I'm encountering:

Runtime Error Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined

Answer №1

When this error occurs, it indicates that there are currently no records associated with that key. To address this issue, you will need to perform a check similar to the following:

this.fetchData(key).then((data) => {
  var newData = [];//initialize an empty Array
  if(data){ //if there is data available for the specified key
     newData = JSON.parse(data); //parse the data and assign it to newData
  }
  newData.push(info); //This step will be executed whether or not there was existing data
  this.saveData(pk, JSON.stringify(newData));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve tasks from Teamweek using jQuery

I need to integrate the planning tool from Teamweek into my JavaScript application using their API. function retrieveTeamweekPlanning() { var apiURL = 'https://teamweek.com/api/v2/', apiKey = '1234567', obje ...

Is there a method to extract a bounding box from a Object3D in three.js?

I have successfully loaded an OBJ file with Three.js and OBJLoader.js. The returned object is a Three.Object3D that contains the typical properties of a 3D model (position vector, up vector...) My current challenge is determining how to obtain a bounding ...

Angular filtering arrays of data

$scope.currentEvent = Object { item_id: "10535", name: "johnny", user_type: "1",category_id: "5"}, Object { item_id: "10534", name: "smith", user_type: "1",category_id: "6"}, Object { item_id: "10536", name: "Greg", user_type: "1",category_id: "7"}; $sco ...

Using AJAX along with the append method to dynamically add identical HTML content multiple times to a single element

Although I have successfully implemented most of the desired functionality with this JavaScript code, there is a persistent bug that is causing unnecessary duplicates to be created when appending HTML. Detecting Multiples The problem lies in the fact tha ...

"Is there a JavaScript code snippet that can retrieve information from a JSON file

Is there a way to create a custom JavaScript function that can extract specific data from a JSON object based on certain keywords? I am working with a Task Manager API and would like to automatically populate fields based on the task title. Here is an exam ...

Move items from one list to another using JavaScript

In my scenario, I have a userlist that is populated from a database. Below is the implementation of the Userlist: <select id="Userlist" name="cars" runat="server" multiple="true" style="width: 270px; height: 200px;"> </select> The objective i ...

Retrieving information from a hyperlink or input field within a list using jQuery

I'm working with the following script : <script> $().ready(function(){ $('.request_list').click(function(){ requesting_dept = $('#requesting_department_name').val(); alert(requesting_dept); $. ...

ng-repeat and $scope problem

I am having an issue with my page where I display 3 images in a row using Ng-repeat. When I click on any image, it only shows the first image that was displayed in that particular row. Template: <div id="galscrolldiv" class="row" ng-repeat="image in i ...

How to compare and link two sections within a JSON file using C#?

Beginner inquiry. I have successfully parsed a JSON file within my program that contains semi-complex data. Below are the relevant excerpts: { "version": "36", "released": "20220223", "samples": ...

Is there a different method for looping in JSX besides .map()?

In my JSX code, I am attempting to display a specific value based on certain conditions. The current code snippet checks if the 'item.result' exists and has a length greater than 0. If so, it maps through the 'item.result' array and dis ...

Converting JSON data into an object using a deserializer

I'm currently working on deserializing some JSON data into a .NET class: {"reset": true, "cursor": "xxxx", "has_more": true, "entries": [ ["/ict", { "revision": 22, "rev": "16010e2631", "thumb_exists": false, "byte ...

"Unlocking the Potential of ReactJS: A Guide to Setting Focus on Components Once They Become

My code had a <div> with a child component named SocialPostwithCSS, and when onClick was triggered, it would hide the div, set the state to editing: true, and display a <textarea>. I used this.textarea.focus with a ref={(input)=>{this.textar ...

Transferring 64-bit data between php/MySQL server using JSON?

I've been developing an application that requires sending and receiving 64-bit numbers through a PHP API using JSON to interact with a MySQL database. I'm unsure about the best way to format these numbers in JSON to avoid losing precision. Should ...

What are the best practices for transmitting and receiving data with React Router?

I have a project that includes both react-js and normal javascript components. I've successfully figured out how to navigate between the two, but now I want to send data between them as well. Here's the code snippet I currently have: <BrowserR ...

``Look at that cool feature - a stationary header and footer that stay in place

I'm seeking advice on how to design a website with a fixed header and footer that remain consistent across all pages, with only the content area altering. I've come across a site as an example - , but couldn't figure out how it was done even ...

Modifying characters within a designated class definition

I'm working on integrating Isotope with a CuteNews system, and in order to make the filtering function properly, I need to include some identifiers in my class declaration for each isotope item. Link to Isotope In CuteNews, my news items can have mul ...

How can you utilize multiple files to set environment variables in Node.js?

My project has two different environments for development and production production.js var config = { production: { session: { key: 'the.express.session.id', secret: 'something.super.secret' }, ...

What is the best way to determine the number of objects in a list based on

When I deserialize a JSON like this: files = JsonConvert.DeserializeObject<Files>(json); I am trying to count the instances of natives-windows and artifact, so I have used lambda expressions, but I keep getting a NullReferenceException. files.libra ...

Deciphering JSON data and assigning it to a variable

Querying SWIFT4 JSON Data from FIREBASE Is there a way to extract the email and username from a parsed JSON into variables? Also, how can I store citiesName data into an array called citiesName? struct User: Codable { let email: String let username: St ...

When attempting to retrieve JSON data from a web server using my ESP8266 and HTTP requests, I am receiving HTML content instead of the expected JSON format

I am facing an issue with retrieving JSON data from my web server. Instead of receiving the expected raw JSON content, I am getting an error message embedded within a script tag. I need help troubleshooting this problem. #include <ESP8266WiFi.h> #in ...