简体   繁体   English

NativeScript Typescript:JSON数组到Typescript类型化数组

[英]NativeScript Typescript: JSON Array to Typescript Typed Array

I need your help, I'm learning NativeScript, here I read the txt file which has JSON data below output. 我需要您的帮助,我正在学习NativeScript,在这里我阅读了txt文件,该文件在输出下方具有JSON数据。 After I fetch them I want to assign it to Array countries. 提取它们后,我想将其分配给Array国家。 But no luck :( 但是没有运气:(

public countries: Array 公共国家:数组

console.log(response) console.log(响应)

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

Output: 输出:

[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ] [{“名称”:“阿富汗”,“代码”:“ AF”},{“名称”:“阿尔巴尼亚”,“代码”:“ AL”}]

Please help. 请帮忙。 Regards, 问候,

This is an Array<any> : 这是一个Array<any>

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

You need to convert it to a Array<Country> , Example: 您需要将其转换为Array<Country> ,例如:

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

That, or you can change the return of the function that reads the txt to Array<Country> 那,或者您可以将读取txt的函数的返回值更改为Array<Country>

finally got it via below code... 终于通过下面的代码得到了...

                    let elements: Array<Country> = JSON.parse(JSON.stringify(response))
                    .map((item:Country) => 
                    {
                        console.log(item.name +  ' < - >' + item.code);
                    })

Thanks All :) 谢谢大家:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM