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

acquire data from a JSON array

Attempting to extract the SKU from a URL www.mbsmfg.co/shop/coles-grey/?format=json-pretty in JSON format, and display available values under variants for that specific product to users. For example, when a user visits www.mbsmfg.co/shop/coles-grey/, th ...

Tips for feeding information into AWS Kinesis using Particle cloud JSON web hooks

Seeking advice or insights on how to transmit a JSON payload for data ingestion into AWS Kinesis. Currently utilizing Ubidots for data visualization, but looking to switch to AWS QuickSights for analysis and visualization purposes. Below is an example of a ...

When aggregating data using Mongoose expressions, Number, Boolean, and ObjectId types are not compatible

I am facing an issue with my query: const match: PipelineStage.Match = { $match: { deleted: false, provinceId: new mongoose.Types.ObjectId(req.params.provinceId), }, }; const query: PipelineStage[] = [match]; const c ...

Challenges with image cropping in Angular causing performance problems

Utilizing this specific component for image cropping within an ionic/angular8 project has been causing severe performance issues, leading to unresponsiveness on mobile devices. Interestingly, the desktop version does not encounter any problems and the crop ...

Strip the quotes from the JSON output

Need help removing double quotes from my JSON output. Here's the issue: [{"id":"1","nom":"Magasin Jardins 2","ville":"Paris","latlng":["36.85715,10.127245"]} I want to remove quotes from the latlng value to get this result: [36.85715,10.127245] He ...

Tips for Implementing Error Handling in Angular using Sweetalert2

On this code snippet, I have implemented a delete confirmation popup and now I am looking to incorporate error handling in case the data is not deleted successfully. confirmPopUp(){ Swal.fire({ title: 'Are You Sure?', text: 'Deleti ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Can fields from one type be combined with those of another type?

Is it possible to achieve a similar outcome as shown below? type Info = { category: string } type Product = { code: string, ...Info } Resulting in the following structure for Product: type Product = { code: string, category : string } ...

What method can be used to inherit the variable type of a class through its constructor

Currently, I am in the process of creating a validator class. Here's what it looks like: class Validator { private path: string; private data: unknown; constructor(path: string, data: string) { this.data = data; this.path = path; } ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...

Organizing items into categories using a two-dimensional array with jQuery

My goal is to organize my items by category, displaying them as follows: Category A Item 1 Item 2 Category B Item 1 Item 3 Item 4 Category C Item 3 Item 4 I have an array that contains the necessary data. How can I efficiently print the categori ...

Updating the displayed data of an angular2-highcharts chart

I am facing an issue with rendering an empty chart initially and then updating it with data. The charts are rendered when the component is initialized and added through a list of chart options. Although the empty chart is successfully rendered, I am strugg ...

Is there a way to retrieve a nested object from a JSON string that may be considered invalid?

I received this data from an API response {\r\n \"VAL_VER_ZERO_TURN\" : {\r\n \"J_ID\" : \"345\",\r\n \"DIS_CODE\" : \"WV345\"\r\n }\r\n} After us ...

Implementing Dynamic Component Rendering in React Native with Typescript

For the past 3 hours, I've been grappling with this particular issue: const steps = [ { Component: ChooseGameMode, props: { initialValue: gameMode, onComplete: handleChooseGameModeComplete } }, { Com ...

Utilizing angular.forEach in $scope to extract data from an array

I am working with a dynamically changing array based on another piece of code and I am attempting to extract specific data from it. Here is an example of one dynamically generated array stored in $scope.filtereditem: [{ "active": true, "createdAt": " ...

Implementing a feature in ReactJS that allows users to upload multiple images in base64 format

I'm trying to develop an image uploader using base64 and I want the output as an array. However, I am encountering an issue where the array is coming out empty!. I suspect it might be due to an asynchronous problem. Any tips on how to incorporate asyn ...

Creating a versatile JavaScript/TypeScript library

My passion lies in creating small, user-friendly TypeScript libraries that can be easily shared among my projects and with the open-source community at large. However, one major obstacle stands in my way: Time and time again, I run into issues where an NP ...

Transforming an object into an interface in TypeScript

Recently, I have started learning Typescript and am currently working on a project where I am building a REST API. In this project, I have defined a specific model for my request payload. However, even after typecasting, the type of 'resObj' rem ...

Error: Unable to iterate through posts due to a TypeError in next.js

Hi there, this is my first time asking for help here. I'm working on a simple app using Next.js and ran into an issue while following a tutorial: Unhandled Runtime Error TypeError: posts.map is not a function Source pages\posts\index.tsx (1 ...

Encountering issues launching cmd.exe using ProcessStartInfo

Web.config: <appSettings> <add key="MystemDirectory" value="D:\mystem\"/> </appSettings> Controller: if (flag) { db.FbDocuments.Add(fbDocument); db.SaveChanges(); var workingPath = WebConfigurationManager.Ap ...