Retrieving values from a nested array within a JSON object

When making a GET request, the JSON object returned has this structure:

{"ID":5176,
"DateFrom":"8/29/2018",
"DateTo":"8/29/2018",
"Units":[{"Key":"Value","Key2": "Value2"}]
}

The issue is with accessing the value of Units[0]. I've attempted the following:

testFunction(){
this.service.getJSON(params)
.subscribe((data) => { 
  this.model = data;
  this.dateFrom = this.model.DateFrom;
  this.dateTo = this.model.DateTo;
  this.unit = this.model.Units.Key;
  console.log(this.unit); //undefined
  }); 
 }
}
ngOnInit() {
this.testFunction();

}

Any ideas on what might be missing or causing this problem?

Answer №1

It is recommended to utilize

this.unit = this.model.Units[0].Key;

in place of

this.unit = this.model.Units.Key; 

as Units.Key is not defined

Answer №2

Given that Units is an array of JSONs with only one element, it should be accessed using Units[0].

Once Units[0] is a JSON, the Key property becomes essential. There are two ways to access it:

  1. Units[0].Key
  2. Units[0]['Key']

The final code snippet will resemble this:

testFunction(){
this.service.getJSON(params)
.subscribe((data) => { 
  this.model = data;
  this.dateFrom = this.model.DateFrom;
  this.dateTo = this.model.DateTo;
  // First method
  // this.unit = this.model.Units[0].Key;
  // Second method
  // this.unit = this.model.Units[0]['Key'];

  console.log(this.unit); // undefined
  }); 
 }
}
ngOnInit() {
this.testFunction();
}

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

What is the best method for excluding attributes from a nested model in sequelize?

In my project, there are 2 models called User and Role, and they have a many-to-many relationship. To manage this connection, I introduced a third model named UserRole. The issue arises when the UserRole is also retrieved in the query below: async getUser ...

Can the month dropdown in react-datepicker be modified to display numbers instead of names?

Here is the code I have: <DatePicker selected={value?.toDate()} onChange={(date) => this.handleMonthChange(date)} inline showMonthYearPicker dateFormat={this.props.formatString} /> https://i.sstatic.net/SkdGP.png I am seeking ...

Encountering an installation issue with Angular 2 data table

Is there a solution for resolving unmet peer dependencies during the installation of Angular 2 data table? Here is the issue I am encountering while trying to install it. https://i.sstatic.net/HcirY.png ...

Navigating the world of streams in JavaScript

Is there a way to manipulate arrays in JavaScript in a similar manner to Java Streams? For example: arr.map().map().map() Currently, this would only perform a single iteration. How can I accomplish this without using a library? ...

Routing in Angular 2 with .NET Core

I am experiencing an issue with my ASP.NET CORE app that utilizes angular2 routing. When I run the app locally, the routes work as expected. However, once I publish it to the server (running IIS 7), the routes seem to resolve to the server root instead of ...

The upload cannot be completed as the file upload is not in a multipart request format

This file upload code was referenced from this source. The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload. I have confirmed ...

Out of the blue, Angular has inexplicably ceased to function in development, production, and local environments, despite successfully

TypeError: n is not iterable TypeError: n is not iterable I am currently working on an Angular and Node.js project hosted on Heroku. Everything was running smoothly until recently when I encountered an error after successfully building Angular. Upon loadi ...

Eliminating blank attributes within an array of objects

I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they ...

Display exclusively unique values within a dropdown menu

I need assistance with a form that contains a drop-down menu. The form is linked to a products table, where one of the fields is 'mfg name'. Currently, the code provided below displays the manufacturer for EACH product, but I am looking to have a ...

Is it necessary to conceal Angular navigation controls when the user is not authenticated?

In Angular, is there a standardized method for hiding controls when the user is not logged in? We already have the CanActivate guard which checks if a user can access a route. Would it be better to hide the route initially if the user is not logged in or l ...

How can I fill a FormArray within a Mat Table?

I've been attempting to construct a material table using FormArray, but I've encountered an issue with the formContolName not being set. Here is the code snippet I've put together: TS form = this.fb.group({ production: this.fb.array([this ...

Record the variable as star symbols in the VSTS Extension

I am working on a VSTS extension using Typescript and utilizing the vsts-task-lib Currently, I am encountering an issue with the execSync function, which displays the command being executed. However, I need to hide a token obtained from a service by displ ...

Getting the value from an Observable in Angular 2 after using the CanActivate guard and subscribing

I am using a "CanActivate" method in my web service to check if the user is logged in. The "CanActivate" method returns an Observable. My main concern is how to retrieve this boolean value so that I can adjust my view based on whether the user is connecte ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dog ...

In my current project, I am implementing a feature in Angular 6 to close a Bootstrap modal once the server successfully receives the necessary data

Here, I am working on creating the content for a CRUD component that saves data as needed. My goal is to make the modal disappear once the data is submitted. <div class="container"> <div class="table-wrapper"> <div class="table-ti ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Guide to transforming JSON data into a different structure

My API is currently providing data in this format: [ { "lattitude": 52.57812538272844, "longitude": -1.7111388218750108, }, { "lattitude": 53.043884, "longitude": -2.923782, } ] I need to transform the data ...

Exploring the Power of Typescript and Graphql Fragments

Utilizing codegen, I automatically generate TypeScript types and employ Apollo client to submit requests to the server. However, when I execute code generation for the given example, TypeScript fails to recognize that the people object contains firstName ...