Unable to retrieve value 'includes' from null object

Currently, I am utilizing Vue.js along with JavaScript.

In my code, there is an array of objects named products, each containing a special property called smallest_unit_barcode. My goal is to filter out only those products that have a barcode similar to a given value. To achieve this, I implemented the following 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;
    }
    

While everything seems to be working smoothly, I encountered an issue when

obj.smallest_unit_barcode == null
, resulting in the following error message:

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

My concern now is how to overlook the null value while filtering the products array?

Answer №1

Always check for null before trying to access a property:

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

Using the && operator with short circuiting ensures that the right operand is only evaluated if the left operand is true.

Answer №2

The easiest way to achieve this is by utilizing the question mark symbol in combination with the "includes" method.

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

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

Tips for resolving the error message: 'The "path" argument must be a string. Received type undefined' that occurs when executing 'vue add vuetify'

After successfully creating a new app using 'vue create agenda', I proceeded to cd into the project folder and run 'vue add vuetify' to integrate Vuetify. However, I encountered an unexpected error. I attempted to search for solutions ...

You can interact with our dropdown menu using the tab key, even when it is

We are looking to make our dropdown tabbable when expanded and non-tabbable when collapsed. We attempted using tabindex="-1" on the content inside the expandable div, but this resulted in it being non-tabbable even when expanded. Any suggestions on how t ...

There is a possibility of encountering an endless update loop in the watcher when utilizing the expression "tabs" error in vue

My code includes a watcher on tabs to prevent them from changing based on the values of the edit. If edit is false, then go to the next tab; otherwise, prevent the change. However, when I try to click on the tab heading to change the tab, I encounter an er ...

The functionality of reordering columns, virtual scrolling, and resizing the grid in jqgrid are not functioning properly

Implementing jqgrid with Symfony to display a datagrid has been a challenging task for me. Thanks to Oleg's insightful response, many of the major issues have been resolved. Below is a snippet of my code: <link rel="stylesheet" type="text/css" ...

Encountering an issue: Module """ not located at webpackMissingModule

I'm facing an issue while trying to webpack my express application. Specifically, I encounter the following problem whenever I attempt to access the / page: Encountering Error: Cannot find module "." at webpackMissingModule Below is a snippet of c ...

Performing a PHP Curl request and an ajax query to an ASP.NET page

I am attempting to send an ajax query to an ASP.NET page. Here is the algorithm I am following: 1. There is a form on my webpage; 2. When the user fills in all the fields, they click the submit button; 3. Upon clicking the submit button, JavaScript sends ...

Error: The property 'postID' can not be read because it is undefined

I'm new to programming and I am working on creating a news/forum site as a practice project. I have set up a route /post/postID/postTitle to view individual posts. Initially, when I used only :postID, it worked fine. But after adding :postTitle, whene ...

What are the signs of a syntax error in a jQuery event like the one shown below?

One of my forms has an ID attribute of id ='login-form' $('#login-form').submit(function(evt) { $('#login-button').addClass('disabled').val('Please wait...'); evt.preventDefault(); var postData = ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

MongoDB update operation is incomplete

My model includes fields such as "id," "liked," "likedBy," and "matched." I am updating my database to add an id based on hypothetical likes; it stores the target's id in the current user's liked field and the current user's id in the target ...

Ways to designate a tab as active

Having trouble styling the active tab in my tabbed menu created with Bootstrap. The active class seems to only affect the first tab. How can I make it work for all tabs? Check out this screenshot for reference. Below is the code snippet: <script ...

The significance of 'this' in an Angular controller

Forgive me for what may seem like a silly question, but I believe it will help clarify my understanding. Let's dive into JavaScript: var firstName = "Peter", lastName = "Ally"; function showFullName () { // The "this" inside this func ...

When a class and ID are dynamically applied, the click event may not fire and the CSS may not be applied

Hey everyone, I am facing an issue with declaring id and class when creating a table dynamically. I have tried multiple functions to make my click event work but without success. Can anyone help me with this? Below is the code for my dynamic table where I ...

Pop-up confirmation dialog in JQuery following an AJAX request

In order to validate on the server side whether a person with a specific registration number already exists in the database, I have implemented a process. If the person is found registered, the program flow continues as usual. However, if the number is not ...

Ways to create a back-and-forth transition across a sequence

Is it possible to create an animation that changes the width of an element once, then reverts back after a pause? I want this transition to occur over a three-second interval followed by a two-second delay. How can I achieve this? Below is the code I have ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

Create an unordered list using the <ul> tag

Creating a ul as input is my goal, similar to this example on jsfiddle: http://jsfiddle.net/hailwood/u8zj5/ (However, I want to avoid using the tagit plugin and implement it myself) I envision allowing users to enter text in the input field and upon hitt ...

Ensure the video fills the entire width of its parent element and adjusts its height accordingly to maintain a 16:9

I am looking to make both videos fill 100% width of their parent element while keeping their aspect ratio intact. The parent element takes up 50% of the window's width, so the videos need to be responsive. I have come across numerous solutions that ...