Converting JSON Arrays into Typed Arrays in NativeScript using Typescript

Can someone assist me with a problem I'm facing while learning NativeScript? I am trying to read a txt file that contains JSON data and then assign it to an Array called countries. However, despite my efforts, I have not been successful.

The code snippet I am using is:

public countries: Array

console.log(response)

console.log(JSON.parse(JSON.stringify(response)))

Here is the output I am getting:

[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ]

If anyone could provide some guidance on how to solve this issue, I would greatly appreciate it. Thank you,

Answer №1

Here we have an array of objects representing countries:

[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ]

The current type is Array<any>, but you should convert it to Array<Country>. For example:

result.forEach((e) => { countries.push(new Country(e.name, e.code)) }

You can also modify the function that reads the text file to return Array<Country> instead.

Answer №2

Successfully achieved the desired outcome using the code snippet below:

                    const countries = JSON.parse(JSON.stringify(response))
                    .map((item) => 
                    {
                        console.log(item.name +  ' < - >' + item.code);
                    })

Appreciate everyone's help :)

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 way to utilize my data with Charts.js for my specific situation?

I am utilizing Charts.js in my Angular project (not AngularJS) and I am trying to create a graphic representation with data from my database that shows the distribution between men and women. However, I am struggling to figure out how to loop through the d ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

Getting the initial value of a node from a JSON response by utilizing Groovy

I am attempting to extract the first node value (ResourceItemID which is 2290) from my JSON response. Here is how my Response looks: { "Success": true, "TotalRecords": 41, "RoomSearchResult": [ { "ResourceItemID": 2290 ...

Simplified JavaScript Object Structure

A JSON array that is flat in structure looks like this: var flatObject = [ { id : "1", parentId : "0", name : "object 1" }, { id : "2", parentId : "1", name : "object 2" }, { id : "3", parentId : "2", name : "object 3" }, { id : "4", pare ...

Developing an Angular component using data retrieved from a JSON response

I want to design a model/class for my Angular App using the provided response template: { "id": {integer}, "name": {string}, "make": { "id": {integer}, "name": {string}, "niceName": {string} }, "model": { "id": {string}, "n ...

Resolving "SyntaxError: Unexpected identifier" when using Enzyme with configurations in jest.setup.js

I'm currently facing an issue while trying to create tests in Typescript using Jest and Enzyme. The problem arises with a SyntaxError being thrown: FAIL src/_components/Button/__tests__/Button.spec.tsx ● Test suite failed to run /Users/mika ...

How to Include HttpClient in an Angular Service

Looking for a service that utilizes http requests? import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root&a ...

The jQuery AJAX request returned a JSON result that was labeled as 'undefined'

Having trouble retrieving JSON data with Jquery? If you're seeing 'undefined' results, try using the following code to display the JSON: alert(data); If you're unable to access specific fields like 'first_name', try this ins ...

Struggling with displaying MySQL data in JSON format using Highcharts

Currently, I am attempting to display data from a PHP file on an area graph by using the example found here. Initially, all the data was commented out before being passed to the array. Now, my focus is solely on displaying one portion of the data. I suspec ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

Combining JavaScript JSON objects with corresponding parameters

I'm struggling to find a solution for merging two JSON objects. Despite searching for answers, I haven't found any that have been helpful. My goal is to compare two objects and if there's a match, add an attribute as a marker to the first ob ...

How to Restrict the Number of Rows Displayed in an Angular 4 Table

Currently, I am faced with a situation where I have a lengthy list of entries that I need to loop through and add a row to a table for each entry. With about 2000 entries, the rendering process is slowing down considerably. Is there a way to limit the disp ...

Verify that the zip code provided in the input matches a record in the JSON data and extract the

I need to create a feature where users can input their zip code, check if it matches any of the zones in a JSON element, and then display the corresponding zone: var zones = [{ "zone": "one", "zipcodes": ["69122", "69125", "69128", "69129"] }, ...

Points in an array being interpolated

I am currently working with data points that define the boundaries of a constellation. let boundaries = [ { ra: 344.46530375, dec: 35.1682358 }, { ra: 344.34285125, dec: 53.1680298 }, { ra: 351.45289375, ...

Convert entity to JSON object using JavaScriptSerializer

These are the entities in my system: class Location { public string Country { get; set; } public string City { get; set; } public string Street { get; set; } } class Individual { public string Name { get; set; } public int Age { ...

The TypeScript compilation is missing Carousel.d.ts file. To resolve this issue, ensure that it is included in your tsconfig either through the 'files' or 'include' property

While trying to build an Angular application for server-side execution, I encountered the following errors: ERROR in ./src/app/shared/components/carousel/interface/Carousel.d.ts Module build failed: Error: /home/training/Desktop/vishnu/TemplateAppv6/src ...

What are the differences between displaying JSON data on a Flask interface compared to a Django interface

Currently, I am looking for the simplest method to display data on a web interface using either Flask or Django (whichever is easier). I already have some sample JSON objects available. Could anyone provide recommendations on how to achieve this and whic ...

Why do my index fields continue to display as "analyzed" even though I indexed them as "not_analyzed"?

I am encountering an issue with the data indexing process in Elasticsearch. Despite specifying "not_analyzed" in my Python script, the index field is showing up as "analyzed" in Kibana4 dashboard. The data I have in Amazon SQS is in JSON format and my scri ...