shoffstall's avatar

V-if problem when trying to get nested object

I am using Vue with a Laravel API.

My JSON looks like this:

    [{"id":1,"name":"esse","type_id":2,"type":{"id":2,"name":"Work","type":"phone","created_at":"2020-02-08 03:25:44","updated_at":null,"deleted_at":null,"created_by_id":1,"last_updated_by_id":null}},
    {"id":2,"name":"sunt","type_id":4,"type":{"id":4,"name":"Mobile","type":"phone","created_at":"2020-02-08 03:25:44","updated_at":null,"deleted_at":null,"created_by_id":1,"last_updated_by_id":null}},
    ...
    {"id":53,"name":"Sean","type_id":null,"type":null},
    {"id":54,"name":"Tim's test tag","type_id":null,"type":null}]

My Vue code looks like this:

<article v-for="tag in tagList" v-bind:key="tag.id">
            <h1>{{ tag.name }}</h1>
            <p >{{ tag }}</p>
            <div v-if="tag.type_id !==null" >
                <p v-for="tagType in tag.type" :key="tagType">{{ tagType.name }}</p>
            </div>
        </article>

As you can see in the data the last two elements have type_id = null. Even though the v-if explicitly checks to see if it is null or not, it still tries to loop the v-for on the paragraph tag and thus throws an error that it Cannot read property 'name' of null. Where am I going wrong?

Thank you

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Type isn't an array but an object

<div v-if="tag.type_id !==null" >
              <p>{{ tag.type.name }}</p>
            </div>

Please or to participate in this conversation.