Converting a JSON array into a TypeScript array

Looking to convert a JSON array into a TypeScript variable array.

The JSON data retrieved from http://www.example.com/select.php:

{ 
     "User":[ 
      {"Name":"Luca M","ID":"1"},
      {"Name":"Tim S","ID":"2"},
      {"Name":"Lucas W","ID":"3"} 
     ] 
    }

Desired output array:

  this.items = [
          'Luca M',
          'Tim S',
          'Lucas W'
        ];

UPDATE:

Current code snippet:

 this.http.post('http://www.example.com/select.php', creds, {
          headers: headers
      })
          .map(res => res.json().User) 

          .subscribe(
          data => this.data = data.User.map(user => user.Name), 
          err => this.logError(err),
          () => console.log('Completed')
          );


      this.items = this.data;

Error message received:

Cannot read property 'map' of undefined

Any suggestions on how to resolve this issue?

Thanks and regards,

Answer №1

Looking at this specific json structure:

const jsonData = {
    "Users": [
        { "Name": "John D", "ID": "1" },
        { "Name": "Sarah P", "ID": "2" },
        { "Name": "Mike L", "ID": "3" } 
    ] 
}

const userNames = jsonData.Users.map(user => user.Name);
console.log(userNames); // ["John D", "Sarah P", "Mike L"]

(view playground code)

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 would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

Merging two NSDateFormatters to create a unified format

At the moment, I have two NSDateFormatters utilized in my application and I am looking for a way to consolidate them as they are both parsing the same date. I maintain a NSObject named UpcomingReleases where all my JSON information is stored. In Upcoming ...

Vue: Optimizing JSON response filtering

I am struggling with filtering a JSON response using Vue. return this.offers.filter(type => type.offers == 'Junior'); When I keep it as return this.offers, the following is displayed in my HTML: {"-MN5agCddYAdy7c8GSSz": { "comp ...

Transforming various types of arrays all at once, rather than individually processing each element

Out of sheer curiosity: I am exploring a theoretical problem dealing with optimizing the use of data structures in applications. For instance, consider the following types (currently utilizing DXE7): type TMyType1 = 0..4294967295; TMyType2 = 0..65535 ...

An issue occurred while attempting to serialize or deserialize data with the JSON JavaScriptSerializer. The length of the string exceeds the allowable limit

""""""""""""""""""Issue encountered during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the maximum value set on the maxJsonLength property.","StackTrace":" at System.Web.Script.Serializatio ...

Why am I encountering an issue while trying to access req.user.id?

Having set up passport authentication on my express, node project, I encountered an error when trying to access req.user. The error message displayed is Property 'id' does not exist on type 'User'.ts(2339). Below is the relevant code sn ...

How can I effectively filter the data returned by consuming an API in JSON through an Angular service?

My Angular 6 project includes a UsersService that is injected into the UsersComponent. Originally, the component displayed mock data in the form of a string array. However, it now consumes JSON data from an API provided by JSONPlaceholder via the UsersSer ...

Angular's DecimalPipe will truncate any strings that exceed 10 digits

Using the decimal pipe to format numbers in an input field value| number:'0.0-6': 'en-us' When working with numbers containing more than 10 digits, it displays as follows: For 11111111111.123456, it formats to 11,111,111,111.123455 ...

Setting up state using the useState hook in a Typescript environment

At some point in the future, the state will be updated using the useState hook with an array of objects. The interface for this array of objects will look like this: export interface DataSource { dataPiont: Array<DataPoint>; } export interface Dat ...

Exploring a collection of objects using a filter and specific keyword

I am looking to implement a search functionality in JavaScript using an array, filter, and keyword. The goal is to search through the array based on the filter and keyword provided, and return a new array of objects similar to the original one. var data ...

What is the best way to send props to a child component in JSX with TypeScript?

While passing props to the child, I encountered an error message stating "Property 'isClicked' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes". I defined "isClicked?: boolean" in my code. What additional steps sho ...

Struggling to extract the objectForKey value as an NSString

Update: I apologize for any confusion in my previous post due to the late timing of its submission. To clarify, I am currently working on an app that should be placing pins on an MKMapview. Although the app runs without any compile errors, the expected ou ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

Using Systemjs to transpile TypeScript async functions

When I manually build .ts files using the tsc tool, I notice that wrappers are generated for async/await keywords. However, I am facing an issue setting up transpile on-the-fly using SystemJS. Here is my index.htm configuration: <script src="https:// ...

Creating a JSON builder using arrayJson in Groovy is an effective way to easily

I'm a beginner in Groovy and I'm trying to create a JSON object using the builder { "query": { "bool": { "must": [ { "bool": { "should": [ ...

Working with MongoDB to index a JSON array within a document using Java

My database in mondoDB contains documents with the following structure: "id":"documentId" { "listOfcards": [ { "cardId":1, "drawingpath": [ { "strokeId":1, "strokePoints": [ ...

The @Until annotation in Gson does not appear to be functioning as anticipated

According to my interpretation of the @Until annotation described in the documentation, it includes all versions up to and including the version specified in the annotation. Documentation: public class User { private String firstName; private Stri ...

Breaking down an array into function arguments in TypeScript/JavaScript

I am working with an array of object instances that have different types. var instances: any = []; instances["Object1"] = new TypeA(); instances["ObjectB"] = new TypeB(); Each type has its own methods with unique names and varying numbers of arguments. I ...

Tips for concealing axis labels in a Python Pandas dataframe

I have created a dataframe using the code below, aiming to use it as input for a seaborn plot. data_array = np.array([['index', 'value']]) for x in range(len(value_list)): data_array = np.append(data_array, np.array([[int((x + 1)), ...

List of characteristics belonging to objects contained within an array

Consider the following array of objects: data = [{x: 1, y: 2, z: 3}, {x: 4, y: 5, z: 6}, {x: 7, y: 8, z: 9}] Is there a way to extract only the x elements from these objects and create an array out of them? For example: x = [1, 4, 7] Can this be achiev ...