1

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,

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks buddy, surprisingly foreach was given error finally solved as above.
1

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

2 Comments

That is working fine in one condition the JSON OUTPUT elements labels, in this case: name and code [ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ] TO BE THE SAME like the object, in this case Country, properties names
One more thing, do you try to print-out the elements array variable, console.log(elements)? In my case the result was: [undefined, undefined]. Any clue why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.