Guide on implementing short-circuit evaluation in Vue method?

Recently, I have been working with vue-cli and vuex to implement a specific functionality. Here is the code snippet that showcases my current progress:

methods: {
filtered() { 
  let vol = this.$store.state.data[1].data.filter(i => i.type === 'vol')[0].measure || 0;
  let weight = this.$store.state.data[1].data.filter(i => i.type === 'weight')[0].measure || 0;
 }
}

In my data, there exists a 'vol' type but no 'weight' type, hence I want the variable weight to be set as 0.

However, I encountered an error stating

Cannot read property 'measure' of undefined
.

If anyone has any suggestions or solutions to this issue, please feel free to share. Thank you in advance!

Answer №1

If you find yourself using filter(), consider switching to find() and saving the result in a variable. Then, verify if the variable has any content.

methods: {
    filtered() {
      let volobj = this.$store.state.data[1].data.find(i => i.type === 'vol')
      let vol = volobj ? volobj.measure : 0;
      let weightobj = this.$store.state.data[1].data.find(i => i.type === 'weight')
      let weight = weightobj ? weightobj.measure : 0;
    }
}

Answer №2

Solution :

  • filter() method in arrays will return an Array, while the find() method will retrieve the first element of the result.
  • To set a default value, use : { measure: 0 }. If nothing is found, this default value will be used as a fallback.
methods: {
    filtered() {
      let volume = (this.$store.state.data[1].data.find(item => item.type === 'volume') || { measure: 0 }).measure
      let weight = (this.$store.state.data[1].data.find(item => item.type === 'weight') || { measure: 0 }).measure
    }
}

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

Add a text description to the textarea when you upload an image

I have a Vue.js file upload feature that I am enhancing by adding a textarea for users to include a description about the uploaded file. Despite my efforts, I am struggling to make this functionality work as intended. The ultimate goal is to send these fil ...

The strategy of magnifying and shrinking graphs on Google Finance for better analysis and

I am seeking to understand the logic behind a zoom-able graph similar to the one on Google Finance. I am aware that there are pre-made components available, but I am interested in a simple example that breaks down the underlying logic. ...

How to combine two fetch calls in Nuxt3?

I have been attempting to chain two fetch calls in Nuxt3, where the second call is dependent on the result of the first one and I need to use the resulting "variable" in a Vue component. My current approach is: <script setup> const url = "myurl ...

Experiencing peculiar behavior with the delete keyword in JavaScript

Okay, so here's the deal... var obj = people[0]; obj.oAuthID = null; delete obj.oAuthID; This code snippet returns... { "uuid": "39b2b45f-1dde-4c9a-8765-1bc76f55848f", "oAuthID": null, "date": "2013-10-21T16:48:47.079Z", "updated": "2013-10 ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...

It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data. How should I approach this? Should I use conditional ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it. export default { name: 'Home', components: { PokeList, FilterType, SearchPokemon}, data() { r ...

Error encountered in jQuery validation: Uncaught TypeError - $(...) ""valid is not a function" is displayed with proper references and order

When I try to call a function, I keep getting an error message that says "Uncaught TypeError: $(...).valid is not a function"... JS $('input[data-val=true]').on('blur', function() { $(this).valid(); }); HTML <div class="col-x ...

Echo input and refresh on the current page upon submission

I am facing an issue with refreshing the page after submitting a form. I want to refresh the page so that the login attempt can be counted, but currently, the form is displayed without the page being refreshed to add to the count. This is my current code s ...

Can someone please advise me on how to output the value of a var_dump for an array using console.log?

After writing the code in this manner, it functions properly and returns a JSON object. public function getElementsAction() { $currency = App::$app->getProperty('currency'); if(!empty($_POST)) { $sql = 'SELECT name, p ...

Customize a jQuery tab plugin to show a particular tab upon initialization [with JSFiddle example]

Currently, I am utilizing the jQuery tabs demo by Jack Moore from . However, I require a modification in the JS to initially display a specific tab (modifying the URL is not feasible for my intended scenario). I have everything prepared in this fiddle: ht ...

The jQuery AJAX function executing twice upon click

I've encountered an issue while attempting to make two Ajax calls on a single page using jQuery. The first Ajax call executes successfully and generates the desired results. However, the second Ajax call is meant to be triggered by clicking a button b ...

Assign the mapState function to dynamically retrieve state objects from the Vuex store within the component

I am currently working on developing a watchlist using Vue3 and Vuex. The goal is for a watchlist component to subscribe to a symbol and receive updates from the store related to that specific symbol. However, if the subscription is removed from the compon ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

What are the steps to store and access state variables using session storage in a React application?

I am currently utilizing React version 18.2.0. In my application, I have a component called BodyComponent that stores the data retrieved from an API call in its state as results, along with some filter information in filters. The BodyComponent fetches the ...

Tips for extracting popular song titles from music platforms such as Hungama or Saavn

I am looking to retrieve the names of the top trending songs/albums from platforms such as Hungama or Saavn. I experimented with web scraping packages available on npm to extract data from websites, including cheerio, jsdom, and request. Eventually, I came ...

Restrictions on the number of characters based on the size of fonts in an html list sc

Recently, I attempted to implement a ticker message on my website using li scroller. However, it appears that there is a limitation on the number of characters that can be displayed in the ticker message when different font sizes are used. With a smaller ...

Error encountered while executing the yarn install command: ENOTFOUND on registry.yarnpkg.com

Typically, when I execute the yarn install command, it goes smoothly without any complications. However, lately, when using the same command, I am encountering the following error: An unexpected error occurred: "https://registry.yarnpkg.com/@babel/core/- ...