Checking for null values in a filter test in Javascript

Seeking guidance on how to implement null testing in my filter. The current setup works well unless any of the fields contain a "null" value. In such cases, an error is thrown:

TypeError: Cannot read property 'includes' of null

Thank you in advance for any assistance provided!

        computed: { 
            items () {
                    return this.keyword
                    ? this.records.filter(item =>
                        item.name.includes(this.keyword) ||
                        item.location.includes(this.keyword) ||
                        item.status.includes(this.keyword) || 
                        item.vendor.includes(this.keyword) ||
                        item.model.includes(this.keyword) ||
                        item.serial.includes(this.keyword) ||
                        item.product_number.includes(this.keyword)

                    )
                    : this.records
            },
        }

Answer №1

If you're looking for a way to safely access nested properties in JavaScript, you can leverage something known as Optional Chaining.

return this.keyword ? this.records.filter(item =>
                        item.name?.includes(this.keyword) ||
                        item.location?.includes(this.keyword) ||
                        item.status?.includes(this.keyword) || 
                        item.vendor?.includes(this.keyword) ||
                        item.model?.includes(this.keyword) ||
                        item.serial?.includes(this.keyword) ||
                        item.product_number?.includes(this.keyword)

                    )
                    : this.records

Answer №2

The reason for the errors occurring is due to at least one of your object properties being set to null. To resolve this issue, I recommend creating a new function specifically designed to handle all use cases and null checks.

computed: { 
    items () {
        return this.keyword
            ? this.records.filter(item =>
                this.checkProperty(item.name) ||
                this.checkProperty(item.location) ||
                this.checkProperty(item.status) ||
                this.checkProperty(item.vendor) || 
                this.checkProperty(item.model) ||
                this.checkProperty(item.serial) ||
                this.checkProperty(item.product_number)
           )
            : this.records
     },
}

checkProperty(prop) {
    return prop ? prop.includes(this.keyword) : false;
}

Answer №3

Create an array of specific keys to use for filtering purposes.

const filterKeys = ['name', 'location', 'status', 'vendor', 'model', 'serial', 'product_number'];

When iterating over the keys, utilize the optional chaining operator ?. to ensure safe property access.

this.keyword
    ? this.records.filter(item => filterKeys.some(key => item[key]?.includes(this.keyword)))
    : this.records

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

Working with Firestore database in React Js may result in an infinite loop

I have connected my React JS app to Cloud Firestore and I am facing an issue with displaying the objects in my JavaScript file. Even though I only have one object in Firestore, it seems to be reading in a loop and I can't seem to identify the cause. ...

Enable players to share their accomplishments from my online game on Facebook

I am currently working on a feature to allow users to share their scores and achievements from my web-based HTML5 game on Facebook. Specifically, I want to: Customize the text that accompanies the post Include a snapshot of their achievement badge by spe ...

Updating the border color in jQuery can be done without affecting the `border-left-color`

I'm working with an element that has the following CSS properties: border: 20px solid; border-color:#4ea88e; border-right-width: 10px; border-left-color: transparent; I need to change the border-color using JavaScript without affecting the border-l ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

Send data containing special characters through a GET request in PHP

I am looking for a way to send any text as a GET parameter to a PHP script. Currently, I am simply appending the text like this: action.php?text=Hello+my+name+is+bob This URL is generated using JavaScript and then used in an AJAX request. In action.php, ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

"Converting an image in Byte[] format to a Base64 string in JavaScript: A step-by-step

Can anyone help me figure out how to convert an image from an SQL database into a Base64 string? The image is currently in the format {byte[6317]}. ...

Implementing a restricted Mongoose promise loop iteration count

Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check i ...

What is the best way to display multiple VR scenes on a single webpage?

Currently, I am attempting to display several 360 photos utilizing the a-frame library through implementing a-scene. However, I am encountering an issue where only one scene is being rendered on my page. Are there any alternative approaches to address this ...

I am looking to create a unique JavaScript variable within my GTM container that will automatically return a value of true when the user approves sharing

Is there a way to trigger a tag when the user shares their location with the browser? I attempted using the following code within a custom JavaScript variable in my GTM Container, but it didn't seem to work. navigator.permissions && navigator ...

What are the steps to turn off Nuxt.js' automatic route generation and instead create a routes.js file manually?

It is common knowledge that Nuxt.js automatically generates routes based on the file structure within the pages folder. My question is, how can I manually define my own routes instead of relying on Nuxt.js to create them for me? Why am I interested in th ...

How can I enable two-finger scrolling on mobile web browsers?

I am currently tackling a project that involves dragging operations on a canvas, making scrolling with a single finger impractical. My goal is to enable scrolling using two fingers instead. After testing different touch-action values, I discovered that pi ...

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Executing multiple ajax calls and retrieving the results: A step-by-step guide

I am looking to run a series of Ajax calls and collect the responses before rendering the results for the user. The current code I am using is not working as expected because the render function is being executed before all the Ajax responses have been ga ...

React JS Material UI disabled button under control

I am looking for some guidance. I am working on a feature where I need to disable a button conditionally. The idea is that if something is selected from my table, then the button should be available; otherwise, it should be disabled. MUI requires a boolean ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

Tips for creating a nested array in Vue.js in the correct way

In my Vue application, I am currently receiving a JSON object structured like this: [ { "meetingName":"ewq", "meetingUrl":"", "meetingPw":"", &qu ...

What is the best way to arrange four divs in a row on a mobile device that is responsive?

I am facing an issue with displaying 4 divs of equal size on my website. In desktop view, they appear side by side but in mobile view, they stack on top of each other. I have tried using display: flex; and bootstrap classes like col-3, col-sm-3, col-md-3, ...