4

I have a Javascript object from a part of a Graph that on some rows may not have all data details

So when I put this on the HTML

{{ip.Out.StockItem[0].Out.Properties.Name}}

VueJS gives this error on console

Unable to get property 'Name' of undefined or null reference"

and does not render the page when the Properties is null.

I tried

{{ip.Out.ItemEstoque[0].Out.Properties?.Nome}}

But then no error, and no page is rendered.

The data comes from a WebAPI and I can not enforce all objects will have all data filled in.

How to solve this?

1
  • The answers worked here, but it would be nice to have some way / option in VueJS to handle those null / missing properties more easily and seamlessy. Commented Jun 24, 2018 at 21:21

2 Answers 2

2

Use ternary if statement.

Following code checks whether ip.Out.StockItem[0].Out.Properties exists and if true get the Name, else displays nothing.

{{ip.Out.StockItem[0].Out.Properties ? ip.Out.StockItem[0].Out.Properties.Name : ''}}

alternativelly you can also use a template

<template v-if="ip.Out.StockItem[0].Out.Properties">
    {{ip.Out.StockItem[0].Out.Properties.Name}}
</template>
<template v-else>
    -NO DATA-
</template>
Sign up to request clarification or add additional context in comments.

2 Comments

This worked well here! I was using a template (more verbose). Thank you! Maybe VueJS could have a setting to ignore null properties / arrays by default.
@Tony According to the creator of Vue.js, it seems not going to happen. github.com/vuejs/vue/issues/4638#issuecomment-270142138
2

if any property can be null or undefined on any level in the object, the most error-free way is to

    {{
        ip &&
        ip.Out && 
        ip.Out.StockItem &&
        ip.Out.StockItem[0] &&
        ip.Out.StockItem[0].Out &&
        ip.Out.StockItem[0].Out.Properties &&
        ip.Out.StockItem[0].Out.Properties.Name
        ?
        ip.Out.StockItem[0].Out.Properties.Name
        :
        ""
    }}

but apparently this is too verbose. A library like https://github.com/erictrinh/safe-access could make your life easier

2 Comments

+1 Very good point! I am trying to return a Graph object from a Azure Functions WebAPI, and I can not guarantee all levels of the object to be filled.
This can be substantially more concise with optional chaining, e.g. ip?.Out?.StockItem?.[0]?.Out?.Propoerties?.Name ?? ""

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.