Uncovering the array within a JSON object using Angular

I am attempting to display an array in the view of my Angular project

Items.json

{
  "tipo": "texto",
  "texto": "A school needs to send 5 students as representatives to a forum on environmental pollution. It was decided that 2 students should be from tenth grade and 3 from eleventh grade. There are 5 prepared students in tenth grade and 4 in eleventh grade. How many different groups can be formed to send to the forum?",
  "respuestas": [
    "9",
    "14",
    "20",
    "40"
  ]
}

TS:

let timeoutMS = 10000;
this.http.get(assets / Items.json)
    .timeout(timeoutMS)
    .map(res => res.json()).subscribe(data => {
        let responseData = data;

        this.preguntas = responseData;
        console.log(this.preguntas);

    },
    err => {
        console.log(err);
    });

The console.log() displays the JSON correctly respuestas is an Array, so it is OK

In the view I receive

preguntas.texto = "A school needs to send 5 students..."
and
preguntas.respuestas = 9,14,20,40
.

When I try to access preguntas.respuestas[0] I encounter this error "TypeError: Cannot read property '0' of undefined TypeError: Cannot read property '0' of undefined at Object.eval [as updateRenderer] ... "

What could be causing this issue?

Thank you for taking the time to read! :D

EDIT:

import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LoginPage } from '../login/login';

import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';

@Component({
  selector: 'page-pregunta',
  templateUrl: 'pregunta.html'
})
export class PreguntaPage {
    userData = null;
    preguntas = {};
constructor(private facebook:Facebook ,  public http: Http) {
  }

ionViewDidLoad() {
    let path = 'assets/Items.json';
    let encodedPath = encodeURI(path);
    let timeoutMS = 10000;

    this.http.get(encodedPath)
    .timeout(timeoutMS)
    .map(res => res.json()).subscribe(data => {
let responseData = data;

this.preguntas = responseData;
    console.log(this.preguntas);
},
err => {
  console.log('error!!', err);
});
}}

Answer №1

If you're looking for an example, consider the following approach:

let answers = []
...
responseData.answers.map(item => answers.push(item)).

After that, you can check the first answer like this:

console.log(answers[0])

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

The user keeps finding themselves redirected back to the Home page rather than the page they are trying

Within my Angular application, users are authenticated through an OIDC provider using the library angular-auth-oidc-client. In the scenario where a user is not authenticated or their session has expired and they attempt to access a page such as https://loc ...

I am curious about utilizing Primeng's MegaMenu component and how I can ensure that my nested menu options properly work with the "routerLink" functionality

Hello, thank you for taking the time to read this message. I want to make it clear that I am new to primeNg and not an expert in Angular either. Overall, the menu is appearing as expected and functioning well. However, I am facing an issue with the dropd ...

Despite specifying a router-outlet on the route, the Angular 2 route is still being loaded into the top level router-outlet

Here is an issue I am facing: https://i.sstatic.net/Ee324.png The scenario involves rendering admin-area-models-models into the router-outlet named models-content. However, it seems to be placed inside the same router-outlet as the parent module admin-ar ...

Node.js callback chaos within the forEach loop

I have a list of venues and I need to determine how many people are currently at each venue. After that, I want to compress the data and convert it to JSON format. The code below is functional, but the resulting JSON is null. var _venues = _.map(venues. ...

Unable to Retrieve Necessary Data Object from Vue Component

Currently, I have been actively developing a project using Vue. One of the components I'm working with is called Subreddit.vue. This component consists of a form in the template that retrieves data entered into the form and assigns it to an object nam ...

What are the steps to parsing JSON data obtained from an API and exporting it to a CSV file?

After working with a weather API that returns data in JSON format, here is an example of the information it provides: { 'data': { 'request': [{ 'type': 'City', 'query': 'Karachi, Pak ...

Managing Prisma error handling in Express

Dealing with error handling using ExpressJS and Prisma has been a challenge for me. Anytime a Prisma Exception occurs, it causes my entire Node application to crash, requiring a restart. Despite looking at the Prisma Docs and doing some research online, I ...

Is there a different way to retrieve the tag name of an element besides using

Currently, I am dealing with an outdated version (Chromium 25) of chromium. My goal is to utilize the tagName method in order to retrieve the name of the specific HTML tag being used. While I am aware that Element.tagName functions for versions 43 and ab ...

Activate the onclick event for HTML select-options when there is only a single option available

My HTML select dropdown features 5 options, which are a list of car manufacturers. When a user clicks on an option, the onchangeHandler triggers to capture the selected value. Based on this selection, another dropdown displaying car models is shown to the ...

Using node express to proxy json requests

In order to proxy requests from a web server to an API server, I am using the code snippet below in my node-express application: app.use('/api', function(req, res) { var url = 'http://my.domain.com/api' + req.url; req.pipe(request( ...

What is the best way to add unnamed functions to an array in Octave?

Can you save anonymous functions in an array? I encountered two distinct errors with different methods: f(1) = @(x) cos(x) f(2) = @(x) -sin(x) f(3) = @(x) -cos(x) f(4) = @(x) sin(x) error: operator =: no conversion for assignment of 'function handl ...

What is the best way to determine the amount of distinct items within an array by utilizing NodeJS?

I have a CSV file with a specific column that contains multiple rows. Each row consists of an array with several elements. Here are four examples of rows from the CSV file: ['Rose', 'Lily', 'Jasmine', 'Rose'] [&apo ...

Steps to duplicate the package.json to the dist or build directory while executing the TypeScript compiler (tsc)

I am facing an issue with my TypeScript React component and the package.json file when transpiling it to es5 using tsc. The package.json file does not get copied automatically to the dist folder, as shown in the provided screenshot. I had to manually copy ...

Using memoization for React Typescript callback passed as a prop

My component is designed to display data retrieved from a callback provided in the props. To prevent an infinite loop caused by mistakenly passing anonymous functions, I am looking for a method to enforce the usage of memoized callbacks. const DataRenderer ...

The C# Twitch Class consistently retains a null value

As a self-taught C# programmer, my knowledge of classes and using JSON data is not as strong as I would like. I have been studying Java in school and applying that knowledge to C#, but I am struggling with deserializing JSON data obtained from an HTTP requ ...

Encountering an issue with installing an angular 2 directive, getting a error message "Cannot read property '0' of

I am attempting to install this using the command prompt like so: PS C:\Users\moshel\Workspaces\Aman.Magar.Maply\WebUI> npm install @ngui/auto-complete --save However, I am receiving the following outcome: npm WARN @angular/[ ...

Executing a function when a user chooses to exit a webpage using the @HostListener('window:beforeunload') method

Utilizing @HostListener('window:beforeunload') allows me to detect when a user navigates away from the page, prompting a dialog window to open. I wish for an event to be triggered or a method to be executed if the user chooses to leave the page. ...

Implementing a variable for an array in Angular 4: A step-by-step guide

I need help determining the correct value for skill.team[variable here].name in Angular, where all team names are retrieved from the skill. Below is the code snippet: HTML <select [(ngModel)]="skill.teams[1].name" name="teamName" id="teamName" class= ...

Using Vue to cycle through an array of objects, and emphasize the chosen item by clicking on it

I have to display an array of objects in the DOM by using map method. Each item has a @click event listener where I want to highlight it with a CSS class 'hover'. The desired functionality is to mimic a menu system where only the clicked item sho ...

Having trouble launching an Angular 2 project

Something strange just happened to my Angular 2 project. Suddenly, I can't seem to start it anymore, and I'm stuck trying to figure out why based on the error messages... node_modules/@types/core-js/index.d.ts(21,14): error TS2300: Duplicate ide ...