1

i am trying to display data from a nested JSON object. The data is retrieved correctly from axios but I dont get it to be displayed.

The json object looks like this:

{
        "id": "1",
        "name": "Germany",
        "continent": "Europe",
        "president": {
            "id": "12",
            "name": "Joanna Doe",
        }
}

In the vue component the data is saved in the "country" object.

. . .
data() {
   country: {},
}

If I then try to render it in vue template, I get all the data if I render following:

<p>{{ country }}</p>

But if I do try to render the data of the nested "president" attribute like this:

<p>{{ country.president.name }} </p>

I get following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
    at Proxy.<anonymous> (CountryDetail.vue:25)
    at renderComponentRoot (runtime-core.esm-bundler.js:1165)
    at componentEffect (runtime-core.esm-bundler.js:5184)
    at reactiveEffect (reactivity.esm-bundler.js:42)
    at effect (reactivity.esm-bundler.js:17)
    at setupRenderEffect (runtime-core.esm-bundler.js:5137)
    at mountComponent (runtime-core.esm-bundler.js:5096)
    at processComponent (runtime-core.esm-bundler.js:5054)
    at patch (runtime-core.esm-bundler.js:4660)
    at componentEffect (runtime-core.esm-bundler.js:5191)

Is there anyway how to render this nested data?

Thanks!

2 Answers 2

2

country is initially an empty object (and later updated), but your template tries to render the nested properties immediately in:

<p>{{ country.president.name }} </p>

That results in an error because country.president initially does not exist, so it's undefined, leading to the error of reading name from undefined.

One way to solve this is to conditionally render that <p> only when country.president is defined:

<p v-if="country.president">{{ country.president.name }}</p>

Alternatively with Vue 3, you could use optional chaining to avoid the runtime error. However, the <p> element would still be rendered with an empty body. (If the empty tag is undesired, stick with the conditional rendering solution above.)

<p>{{ country.president?.name }}</p>
Sign up to request clarification or add additional context in comments.

Comments

2

You are missing a comma , after "continent": "Europe" <- right here.

Your code should work. See this example

1 Comment

I think that's a typo only in the question. Otherwise, the OP would get a SyntaxError before even seeing the TypeError.

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.