If you are looking to achieve this in the template, there is a way to do so, but it may not be the most elegant solution:
<div>{{ jobs[0] && jobs[0].stages && jobs[0].stages[0] && jobs[0].stages[0].node.name }}</div>
You will have to adjust the number of &&
conditions based on how cautious you want to be regarding the presence of nested properties. For example, if you assume that either all data is present or the stages array is null/undefined, you could simplify it like this:
<div>{{ jobs[0].stages && jobs[0].stages[0].node.name }}</div>
However, I would recommend using a computed property to handle these checks and keep your template cleaner. One commonly used function for accessing deeply nested properties is get from lodash. You can import just the get
function without importing the entire lodash
library as shown below:
<template>
<div>{{ stageName }}</div>
</template>
<script>
import get from 'lodash/get';
export default {
props: {
jobs: {
type: Array,
required: true,
},
},
computed: {
stageName() {
return get(this.jobs, '[0].stages[0].node.name', 'missing name');
},
},
};
</script>
It's worth noting that the last argument in the get
function is the default value that will be displayed if any of the properties are missing, such as 'missing name'
.