Guide to accessing the "name" attribute in a JSON array within an Ionic framework

Understanding the Format of JSON Array in LocalStorage

Greetings, I am currently working on an Ionic app and I am relatively new to Ionic and Typescript.

In the image provided below, you can see that I am retrieving my data from an API in a json array format.

Within the TypeScript file, I have written the following code:

` public categoryDetails:any;

const datacat = JSON.parse(localStorage.getItem('categoryData')); this.categoryDetails = datacat.categoryData;`

When I include this line in my HTML file:

<h1 class="business-top">Business of the category {{categoryDetails.name}}</h1>

I encounter an error message stating "TypeError: Cannot read property 'name' of undefined."

I understand that I am not reading the attribute "name" correctly. What is the correct approach to resolve this issue?

Furthermore, how can I display businesses associated with the specific term_id of the category?

Answer №1

To illustrate this concept, you must follow these steps

<h1 class="business-top">Business of the category {{categoryDetails?.name}}</h1>

public categoryDetails: any;

this.categoryDetails = localStorage.getItem('categoryData');

Alternatively, you have the option to utilize Ionic storage, especially if you are working with Ionic framework.

https://ionicframework.com/docs/storage/

import { Storage } from '@ionic/storage';

export class MyApp {
public categoryDetails: any;
  constructor(private storage: Storage) { }

...
  
  // set a key/value
  storage.set('categoryData', 'Max');

  // Or to get a key/value pair
  storage.get('categoryData').then((val) => {
    this.categoryDetails = val;
  });
}

Answer №2

At last, I figured it out.

@Kilomat, your help and advice on using ionic storage were invaluable. They saved me from potential future issues.

As for my JSON file, here's what I did:

In my HTML code:

<ion-grid no-margin>
    <h1 class="business-top">Businesses in the category {{businessData.name}} {{businessData.term_id}}</h1>
    <ion-list>
    <ion-item class="col col-50" *ngFor="let c of BusinessCategoryDetails" text-wrap (click)="product(c)">
      <div *ngIf="c.term_id == businessData.term_id">
      <h2>{{c.post_title}} {{c.term_id}}</h2> <img width="80" height="80" src="{{c.guid}}">
      </div>
    </ion-item>
    </ion-list>
  </ion-grid>

And in my TypeScript code: `var businessCategory: categories = navParams.get("businessCategory"); console.log(businessCategory); /exports the Selected category/

var newData = JSON.stringify(businessCategory);
this.businessData = JSON.parse(newData);`

This extracts properties and values from my previous category page. TypeScript code:

`categories: [categoryDetails] = null;

gotobusiness(category: categories){ this.navCtrl.push(BusinessPage, { businessCategory: category}); }`

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

Showing JSON information in a Django template

I have successfully saved the form values using ajax. The form data is now being stored in the database. My next goal is to display this saved data in a Django template without refreshing the page. Currently, when the form is submitted, only the JSON data ...

What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the passwor ...

I'm having trouble getting my jsonp to function properly. Can anyone help me troubleshoot?

I've been working on my website for the past two weeks, learning HTML, CSS, and a bit of JavaScript. However, I'm facing an issue with the following code that I can't seem to resolve: <head> <script src="http://ajax.googleapis.com/ ...

What is the best way to convert a large amount of uint_8 values into an array of floats within C programming

I've been tasked with reading a file containing unsigned 8-bit integers in binary format and converting them into an array of floats. Typically, I would use the method shown below: uint8_t *s1_tmp = (uint8_t *)malloc(sizeof(uint8_t)*num_elements); fl ...

How can I transform a JSON object into a series of nested form fields?

Can anyone suggest a reliable method for converting a JSON object to nested form fields? Let's consider the following JSON object: {'a':{'b':{'c':'1200'}}}, 'z':'foo', 'bar':{&apo ...

Utilizing pointers in conjunction with a two-dimensional array of a struct and the methods for accessing them through pointers

#include <string.h> #include <stdio.h> struct student{ char last[25] ; char first[25]; }; struct seating { struct student **placement; }; //Set the default values for first and last name void initialize_student_default(struct stu ...

Deleting a key from one object will also remove that key from another object - JavaScript

I have come across an interesting issue with my Javascript code. I am working with two objects, dict1 and dict2, where I need to maintain a form of state and then post the final object. When I click on certain buttons, I assign dict1 to dict2. However, wh ...

Troubleshooting: Groovy Script with JSON Parameter Configuration is malfunctioning

I am attempting to set up an "Extended Choice Config" parameter. I have written my code in the "JSON Parameter Config Groovy Script," but for some reason, it is not showing up on the "build with parameters" screen. I have tried using both regular JSON and ...

Using Typescript to define Vuex store types

Attempting to create a TypeScript-friendly Vuex store has been quite the challenge. Following instructions outlined here, I've encountered an issue where accessing this.$store from a component results in a type of Store<any>. I'm strugglin ...

When attempting to add information, an error occurs stating that the object of type 'dict' does not have the attribute 'append'

Encountered an error: AttributeError: 'dict' object has no attribute 'append'. How can I handle this error when attempting to append data by creating a loop to continuously add values from user input to a dictionary? Is there any method ...

PHP is failing to display line breaks when retrieving data from JSON sources

I have a JSON feed that is decoded by PHP using json_decode and then echoed onto my HTML page. The issue I am facing is that the feed contains \n characters, but when PHP echoes them out, they are not recognized as new lines or line breaks in HTML. In ...

How can I change a relative import to absolute in Angular 6?

Is there a way to change relative imports to absolute imports in Angular 6? Here's an example Instead of using ../../../../environments/environment, can we just use environments/environment instead? ...

What is the method for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...

Using Angular components to manipulate the CSS in the DOM

Struggling with dom manipulation in an angular/node.js environment using typescript for my visualcomponent.html The second inline styling works fine, showing the h1 in blue color. However, I run into issues when trying to embed strings within the innerHTM ...

Exploring the powerful combination of React, Typescript, and the dynamic import Higher Order

import React from 'react' import { Preloader } from 'src/base-components/preloader' import styles from './styles.scss' const withLazyLoading = (importComponent: any) => { return class extends React.Component { ...

Unable to transform a Java string into a JSON array on Android devices

Here's the query to retrieve data from the MySql Database. The data displays correctly in a browser, but an error occurs when viewing it in an Android app: Java.Long.String Cannot Convert to JsonArray if($stem=$con->prepare("select question from ...

The output generated by the PowerShell script does not match the expected JSON format

Issue with PowerShell script execution I have been attempting to generate the following formatted output through my PowerShell script. Desired Output: "TestParam": { "5903-95856-24869-e43": { "CallerName": " ...

Communicating between Angular components

I'm encountering difficulties in establishing communication between two components within Angular. Despite my efforts, I can't pinpoint where I am going wrong. Specifically, I have a table component and I aim to open a modal window (which is a s ...

Using JSDoc with "T extending Component"

get_matching_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[] { return this.components.filter(component => component instanceof component_type_to_return) } In TypeScript, I created a method to retrie ...

The syntax for importing JSON in JavaScript ES6 is incredibly straightforward and

Whenever I attempt to write my code following the ES6 standard and try to import a .json file, it ends up failing on me. import JsonT from "../../Data/t.json" //not functioning as expected var JsonT = require('../../Data/t.json'); //works fine ...