Avoiding errors caused by higher order array methods

Is there a way to avoid errors when filtering data?

The function below may encounter issues at

conversationMember.Name.toLowerCase()
if conversationMember is not present.

This function is part of a computed property in a Vue application. Feel free to ask for more details!

filteredConversations() {
    var self = this;
    var filteredConvos = self.conversations;

    filteredConvos = filteredConvos.filter(conversation => {
        return conversation.MembershipData.some(conversationMember => {
            return conversationMember.Name.toLowerCase().includes(
                self.conversationSearchTerm.toLowerCase()
            );
        });
    });

    return filteredConvos;
},

Answer №1

This doesn't appear to be related to arrays at all.

Based on your code snippet, it appears that conversationMember.Name is expected to be a string (due to the use of .toLowerCase()), indicating that in this context, includes refers to String.prototype.includes, rather than Array.prototype.includes. This assumption is supported by the fact that self.conversationSearchTerm also seems to be a string (as .toLowerCase() is called on it).

The issue arises from using includes on something meant to be a string but isn't. A simple solution is to default it to an empty string if it's falsy:

return (conversationMember.Name || '').toLowerCase().includes(
  (self.conversationSearchTerm || '').toLowerCase()
);

Additionally, you can eliminate the need for var self = this; as this is accessible within your filter due to it being an arrow function. Your function, whether a computed or a method, could be written like this:

filteredConversations() {
  return this.conversations.filter(c => 
    c.MembershipData.some(md => 
      (md.Name || '').toLowerCase().includes(
        (this.conversationSearchTerm || '').toLowerCase()
      )
    )
  );
}

Lastly, to handle cases where any of your conversations lack a MembershipData array, you can default it to an empty array dynamically:

 ...
   (c.MembershipData || []).some(md => 
 ...

If a conversation lacks an array in its MembershipData, the function will then exclude it from the result - since calling .some(condition) on an empty array will return false.

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

Ways to remove specific characters from the escape() function in express-validators

When using the check method from express-validator to validate user input, I'm curious if there's a way to exclude certain characters from the test. For example, currently I have: check("profile.about").trim().escape() This code snippet convert ...

apply background color to Vue list

Can anyone assist me with changing the background color of an active list item? I would greatly appreciate any help. I am currently utilizing the v-for directive in an HTML tag to display a list generated from a data function. However, I am puzzled on how ...

How can I attach a cookie to a div that becomes visible after a few seconds of video playback?

After 20 seconds of video play, a div element appears. I am trying to set up a cookie so that once the div is shown, it continues to appear unless the user clears their cache (cookie logic). This is my current attempt - http://jsfiddle.net/9L29o365/ Any ...

The "model" feature appears to be inactive

I discovered a fiddle with a simple radio button functionality that I forked and made some modifications to. The changes worked perfectly, you can check it out in this fiddle: Vue.component('radio-button', { props: ['id', 'v ...

What is the best way to transmit a JavaScript array to a servlet via AJAX?

Within a textarea, users input one or more email addresses separated by commas. Here is my JavaScript code: var emails = $("#emails").val().split(","); if (emails.length == 0) { window.alert("Please enter an email address."); ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

React version 0.13.3 is throwing an error stating that the Super expression must be either null or a function, not an

I am encountering an issue with the following code snippet: import React from 'react'; import Component from 'react'; import Bar from './Bar.es6.js'; import Chart from './Chart.es6.js'; import { connect } from &apos ...

Leverage JavaScript to update the name of a Google Spreadsheet using the latest data

Here is some code that allows you to rename a document: function renameFile() { var s = SpreadsheetApp.getActiveSpreadsheet(); s.rename("new file name"); } Can you modify this function to rename the file to "new filename 1/18"? Remember, where 18 r ...

jQuery registers the enter event, but does not proceed to trigger the enter action

Hey there, I've been experimenting with jQuery to capture the enter event. Something peculiar is happening though - after pressing enter in the text area, an alert pops up but the text gets entered only after that. Despite trying various solutions, I ...

Utilize Next.js to send an image to an email by leveraging the renderToString function on the API routes

I need help with sending styled emails that contain images. Currently, I am utilizing the renderToString method to pass props into my component. So far, everything is functioning correctly in the API routes. mport client from "@/lib/prisma"; im ...

Error: Attempting to access the `isPaused` property of a null object is not possible

For my Vue front-end app, I'm attempting to integrate wavesurfer.js. However, upon receiving the audio file link from the backend, I encounter the following error: wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isP ...

a reliable approach to gain entry to properties that do not exist

Utilizing Google Apps Script along with JavaScript code, I am leveraging UrlFetchApp to retrieve data from the Stripe API in order to fetch an invoice. Subsequently, the Script processes the retrieved data and updates a Google Sheet template with it. An i ...

Increasing the nth-child Selector in Jquery

Referring to this I am looking to cycle through the nth-child selector, which involves: var i = 1; var tmp = $(this).find('td:nth-child(i+1)'); // I wonder how this can be achieved i++; I have rows with dynamically generated columns i ...

Is it possible for me to create a distinct component that can display numerous input fields at once?

Introducing the inputArea component, which collects data from input fields and sends it to the server: export default class InputArea extends React.Component { constructor(props){ super(props); this.state = { draw_number: '', ...

When the button is clicked, my goal is to increase the value of the text field by one using JavaScript

I need the functionality for each button to increment the value text field located next to it <input type="number" value="0" min="0" max="5" step="1" id="qty"/> <button onclick="buttonClick()" type="button" class="btn btn-success btn-sm" id="add" ...

Test your word skills with the Jumbled Words Game. Receive an alert when

After reviewing the code for a jumble word game, I noticed that it checks each alphabet individually and locks it if correct. However, I would like to modify it so that the entire word is only locked if all the letters are correct. Any suggestions on how t ...

Updating IP addresses in MongoDB

I am dealing with a nested schema in my mongoDB collection. Here's an example of how it looks: { "_id":"61d99bf5544f4822bd963bda0a9c213b", "execution": { "test_split":0, "artifacts&quo ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...

What steps should I take in Three.js to make the "terrain" look three-dimensional?

Currently, I am in the process of developing a 3D terrain using Three.js along with ImprovedNoise.js. Utilizing the examples provided on the Three.js website, I have successfully created what appears to be terrain. However, my issue lies in the fact that i ...

Do not use unnecessary variables for storing references in ES6

Despite using react es6, I am still unsure how to refrain from needing to use the variable that for this scenario: const that = this; UploadApi.exec(file).then(data => { that.setState({ loading : false}); }); ...