Search code examples
javascriptvue.jsmethodsvuexshort-circuit-evaluation

How to use short-circuit evaluation in vue method?


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!


Solution

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