Utilizing a default value for undefined object property in VueJS interpolation

Is there a way to handle undefined object property values in VueJS interpolation by setting a default value? I am working with a computed variable called data that is initially undefined until a selectedDataId is chosen from a selectbox. As a result, Vue throws an error stating "cannot read property 'grandChild' of undefined."

By the way, I am incorporating lodash into my solution.

<div>
    {{ selectedData.child.grandChild }}
</div>

new Vue({
   data: {
       selectedDataId: null,
       selectedData: {},
       data: [ //array of objects here ]
   },
   computed: {
       selectedData() {
           return _.find(this.data, (d) => {
               return d.id == this.selectedDataId;
           });
       }
   }
});

Answer №1

To achieve the desired result, consider implementing the following structure:

{{ selectedData.children && selectedData.children.nestedChild || 'default text' }}

This code snippet effectively verifies the existence of nestedChild and displays "default text" if it is not present.

Answer №2

It appears that you have a redundancy in your code where selectedData is being declared twice within the data object.

If you are encountering issues with it being undefined, you may consider implementing a check for this in your templates using v-if="selectedItem" or in your methods using if (selectedItem).

Instead of relying on lodash, Vue offers a built-in filter method which can be utilized like so:

selectedData() {
    const selectedItem = this.data.filter((item) => {
        return item.id == this.selectedDataId
    })

    return selectedItem.length ? selectedItem[0] : {} // Consider setting to null if no match is found
}

Rather than returning a default object, it might be more appropriate to set the result as null when selectedItem.length equals 0. This way, the checks mentioned above will function correctly since passing an empty object would result in truthy values.

Answer №3

Give this a shot

fetchData() {
    return _.chain(this.data)
        .find({id: this.selectedDataId})
        .defaults(...default object...)
        .value()
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

Transferring a JavaScript variable to PHP using Ajax within the same webpage

Check out my HTML and JavaScript code: <form id="form" action="javascript:void(0)"> <input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font- ...

Map Loader for GeoJson Leaflet Integration

Although my English skills are not perfect, I will do my best to explain my issue. I have some knowledge of javascript / html / ajax and I have created a webgis using Leaflet. The problem arises when loading a large geojson file onto the map - it takes qui ...

Is it possible for the frontend and backend to use a shared package.json file?

Currently, I am working on a small personal project that is housed in a single repository. The backend consists of a Node.js server, while the frontend is built using Vue.js. I am looking to have both components share the same package.json file. The mai ...

What is the best way to eliminate duplicate members from an array of objects by comparing their property values?

The array appears as follows: let example = [ { Time: new Date(1000), psi:100.0 }, { Time: new Date(1000), psi:200.0 }, { Time: new Date( ...

Alter the command from 'require' to an 'import'

Utilizing https://www.npmjs.com/package/json-bigint with native BigInt functionality has been a challenge. In the CommonJS environment, the following code is typically used: var JSONbigNative = require('json-bigint')({ useNativeBigInt: true }); ...

Custom Vue overlay designed specifically for individual cards

I have a Vue project with Vuetify where I am rendering 8 different cards using a for loop. Each card has its own overlay that displays its image when clicked. However, the issue is that when I click on one card, all of the overlays are activated instead of ...

The PHP code embedded within the HTML document and triggered by an AJAX request failed to

Here is an example of my ajax call: function insertModal(link) { $.ajax({ url: link, cache: false, dataType: "text", success: function(data) { $("#modalInput").html(data); }, error: function (request, status, error) { ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

How can Node.js handle an upgrade request effectively?

Dealing with a websocket 'upgrade' event from a Node.js http server presents an interesting challenge - The upgrade handler takes the form of function(req, socket, head) - Is there a method to respond to this upgrade request without access to a r ...

Interacting with an external Android library (Zebra) using Vue JS

I am fairly new to vue.js and currently working on integrating Zebra scanners' callback functionality into a Laravel + Jetstream project that uses Vue on the front-end. Our company utilizes Zebra scanners for stock movement, and I am tasked with brid ...

What is the best way to apply attributes to all titles throughout a webpage?

My goal is to locate all elements on the page that have a title attribute and add a new attribute to each of them. For example: <div title='something 1'></div> <p>Test<div title='something 2'></div></p ...

React - CSS Transition resembling a flip of a book page

As I delve into more advanced topics in my journey of learning React and Front Web Dev, I discovered the ReactCSSTransitionGroup but learned that it is no longer maintained so we now use CSSTransitionGroup. I decided to create a small side project to expe ...

Looking to identify the type of a adorned class in Typescript?

Consider the following scenario: return function IsDefined(object: any, propertyName: string) { .... ] We then go ahead and decorate a property like this: class Test { @IsDefined() p1: String = ""; } Now, when we execute a test inside the ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Troubleshooting Problem with Displaying SVG Images

Snippet for Header Component import React from 'react' const Header = () => { return ( <div> {/* Main-header */} <header className=''> {/* Header-background */} {/* <div c ...

Expanding Your jQuery Library from a Content Delivery Network

As of now, I have a jQuery hosted on my FTP along with other web files. YSlow recommends using a CDN for jQuery. However, I am wondering how I can extend that jQuery. Is it possible to add custom functions to it without being able to edit the original co ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...

I need to generate table rows using v-for and include a unique value in the 'id' attribute of each row

I am creating table rows dynamically in a view using Flask data. <tr id="<% file.id %>" v-for="file in fileList"> <td><img class="thumbnail_preview" src=""></td> <td><% file.filename %></td> <td> ...