0
0
001111112021-06-09 20:24:07
Vue.js
00111111, 2021-06-09 20:24:07

How to get around the "Cannot read property '0' of null" error when accessing multiple empty object properties?

I receive data from the server in the form of an array of objects and through v-for I iterate through the array in

<li v-for="item of data.items" :key="item.id">
      <a class="catalog__pic" href="#">
        <img
          :src="item.colors[0].gallery[0].file.url"
          :alt="item.title"
        />
      </a>
      <h3 class="catalog__title">
        <a href="#">
          {{ item.title }}
        </a>
      </h3>
    </li>

I need to get the value of a property (for example, the property -"url") of each item that is located along this path: AND The problem is that some item objects may not have a colors property, or the property exists but it is empty - null, or absent gallery, which can similarly exist but be null. Thus, it is logical that I get an error from the question. Is it possible to check the existence of the property url item.colors[0].gallery[0].file.url in this access so that if at least one of the properties does not exist, then do not receive an error (in a better way), because. which At the moment I implemented it like this, writing in methods:
item.colors[0].gallery[0].file.url



methods: {
check(item) {
if(item.colors && item.colors[0] && item.colors[0].gallery && item.colors[0].gallery[0] ){
return item.colors[0].gallery[0].file.url
}
return '';
}
}


It works, so we check each individual property, but it looks somehow terrible.
And in the template I pass each item for checking to the check method:

<template>
<li v-for="item of data.items" :key="item.id">
      <a class="catalog__pic" href="#">
        <img
          :src="check(item)"
          :alt="item.title"
        />
      </a>
      <h3 class="catalog__title">
        <a href="#">
          {{ item.title }}
        </a>
      </h3>
    </li>
<template>


If there are several such properties (not only up to the given url of the image) that need to be accessed, then each of them needs to be "expanded" in the condition and each one should be checked sequentially like this .. Or is there a more adequate way?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-06-09
@00111111

https://developer.mozilla.org/en/docs/Web/JavaScri...
https://developer.mozilla.org/en/docs/Web/JavaScri...
But this is from the 2020 standard, to support more older browsers will need babel + preset-env

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question