How to use short-circuit evaluation in vue method?

283 views Asked by At

I'm using vue-cli and vuex and I'm trying to achieve something like this:

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;
 }
}

my current data contains a vol type but not a weight so I'd like let weight to = 0

but I'm getting an error that Cannot read property 'measure' of undefined.

Any ideas would be great, thanks so much!

2

There are 2 answers

0
Barmar On BEST ANSWER

Instead of filter(), use find() and store it in a variable. Then check whether the variable contains anything.

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;
    }
}
0
Ranjeet Eppakayala On

Answer :

  • filter() array helper returns Array where as find() returns first element of result.
  • Set your default value here : { measure: 0 } , If nothing found this will be used as fallback
methods: {
    filtered() {
      let vol = (this.$store.state.data[1].data.find(i => i.type === 'vol') || { measure: 0 }).measure
      let weight = (this.$store.state.data[1].data.find(i => i.type === 'weight') || { measure: 0 }).measure
    }
}