简体   繁体   中英

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. After I fetch them I want to assign it to Array countries. But no luck :(

public countries: Array

console.log(response)

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

Output:

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

Please help. Regards,

This is an Array<any> :

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

You need to convert it to a Array<Country> , Example:

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>

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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