Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'includes' of null"

I'm using Vue.js with JavaScript.

I have an array of objects called products and every object has the property called smallest_unit_barcode. I want to filter only products with barcode like value, so I did this function:

if (value != '') {
    var results = this.products.filter(obj=>obj.smallest_unit_barcode.includes(value));
    var results = results.slice(Math.max(results.length - 20, 0))
    this.pos_quick_lunch = results;
}

Everything works fine, but if obj.smallest_unit_barcode == null, I get this error:

Error in v-on handler: "TypeError: Cannot read property 'includes' of null"

How can I ignore the null value when filtering the products array?

like image 522
softya Avatar asked Sep 12 '25 11:09

softya


1 Answers

Compare against null before you try to access the property:

obj => obj.smallest_unit_barcode !== null && obj.smallest_unit_barcode.includes(value)

Because && is short circuiting, the right operand won't be evaluated if the left operand evaluates to false.

like image 66
Felix Kling Avatar answered Sep 14 '25 23:09

Felix Kling