Encountering a TypeError while attempting to retrieve object values in JavaScript

Having trouble identifying a word that is not in my word list, I keep encountering this error: Uncaught TypeError: Cannot read properties of undefined (reading 'includes') at handleKeyup

Included in my bigwords.js file is the following:

var words = [
    {"id": 1, "word": "abbreviate"},
    {"id": 2, "word": "bamboozled"},
    {"id": 3, "word": "calculator"},
    {"id": 4, "word": "disrespect"}
]

I have an if statement that verifies whether the word is absent from the object.

if (!(words.includes(currentGuess))) {
    document.getElementById('tip').innerHTML = "Word not in dictionary";
    console.log('word not contained in dictionary')
    return
  }

I've attempted various methods to rewrite this without using .includes but haven't found success yet. My goal is for the code to run only if currentGuess does not match any of the words in the list. Thank you!

Answer №1

If your array is structured like the following and currentGuess is a string, you can utilize the includes method:

const words = ["abbreviate","bamboozled","calculator","disrespect"]
words.includes(currentGuess) // true or false

However, if you are dealing with an array of word objects, you should use find, some, or filter to check if currentGuess matches any word value within each object in the words array:

words.find(w => w.word === currentGuess)
// or
words.some(w => w.word === currentGuess)
// or
words.filter(w => w.word === currentGuess).length > 0

For example:

const words = [
    {"id": 1, "word": "abbreviate"},
    {"id": 2, "word": "bamboozled"},
    {"id": 3, "word": "calculator"},
    {"id": 4, "word": "disrespect"}
]

const checkWord = (currentGuess) => {
  if (!(words.find(w => w.word === currentGuess))) {
    // not found
    document.getElementById('tip').innerHTML = "Word not in dictionary";
    console.log('word not contained in dictionary')
  } else {
    // found
    document.getElementById('tip').innerHTML = "Word in dictionary";
    console.log('word contained in dictionary')
  }
}

checkWord('disrespect');
// checkWord('random');
<div id="tip"></div>

Your error may be due to the words array being inaccessible in your scope as mentioned by @Konrad. Nevertheless, the search conditions above are shared for reference.

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

Activate mouseover function automatically for each feature on the leaflet

I'm facing a challenging situation where I need to develop a dashboard application that is similar to the functionality of ChoroplethExample. However, the catch is that I have to loop through all states (Features in geoJSON) and pause for 3 seconds at ...

In order to extract a value from a different webpage, I must first make a request to that webpage and extract the XML value from it

I have been working on a project that requires displaying currency exchange rates. To achieve this, I initially tried using AngularJS to call another webpage for the exchange rate values, but I encountered issues as AngularJS can only make JSON/Rest URL ca ...

What is the best way to retrieve the text from a linked button within my rad grid using jQuery?

I am facing an issue with a grid that contains link-buttons in the code column. The user can check multiple checkboxes, and when they click on the top button of my page, all selected codes will be displayed in a text box on another page using a jQuery func ...

jquery success json ajax datatype

$.ajax({ url: '../ajax/deletestudent.php', type: 'POST', dataType: "json", data: formData, processData: false, // instruct jQuery not to process the data contentType: false, // instruct jQuery not to set contentT ...

There seems to be an issue with Vue JS slots[name$1].every function as it is

I attempted to implement a custom isEmpty function for the Object prototype as follows: Object.prototype.isEmpty = function() { for (var key in this) { if (this.hasOwnProperty(key)) { return false } } return true } However, when tryin ...

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

The Jquery calculation feature sometimes mistakenly adds an incorrect value before calculating the correct value

Working on a calculator that accurately computes the field price and displays it, but facing an issue where the correct answer seems to merge with another value (likely from data-price as they match). Snippet of the code: var updateTotal = function() { ...

Bootstrap Display Password Feature Failing to Function

I am facing a problem with the bootstrap show password eye icon, as it only appears half of it. I have tried everything possible, including: Removing other CSS/SCSS scripts Modifying the append input class. Below is a demo showcasing the issue along ...

In JavaScript, it is not possible to retrieve the maximum or minimum value of an array

Hey there! I'm having some trouble finding the minimum and maximum values in an array. Can you help me figure out what's going on with my code? var repeated, studentsArray = [], marksArray = []; while (repeated !== 'n' && r ...

Utilize UI-Router $stateProvider in Angular run block for Promise Resolution

UI-Router has different capabilities compared to Angular's ngRoute. It not only supports all the features of ngRoute but also provides additional functionalities. I am transitioning my Angular application from ngRoute to UI-Router. However, I'm ...

Error message: "The post request is returning a value of 0

I am trying to pass a variable from JavaScript to PHP using the POST function. Here is what I have tried: The line causing issues: $.post(window.location, {idafevent: event.id}); JavaScript code snippet: eventRender: function(event, element) { elemen ...

Oops! The function 'ModalDemoCtrl' has not been defined, causing an error

Hey there, I'm encountering an error when using angularJS in my project. The project is built on the django framework and does not include any additional JS files. Here are some snippets of my code: JavaScript: {{ ngapp }}.controller("ModalDemoCtrl" ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

What is the solution using high-order functions?

I am struggling with a problem I came across on the internet. The task at hand is to identify all unique elements in an array that are less than 10, calculate the sum of these elements, and then multiply each element in the array by this sum. I have heard ...

Remove all nested object entries

In my coding project, I have a class structure defined as follows: class Foo{ id:string; name:string; childFooIds: string[]; } Within this structure, each instance of Foo can reference its child Foo objects by ID. These Foo instanc ...

Creating a form for adding and editing using React Hook Form

I'm currently working on creating a form that can handle both the creation and editing of a product by passing values through an object. The form functions perfectly for creating a product, but I'm facing challenges in making it work for editing ...

How to retrieve and modify JSON data in Node.js using Stream with both Get and Post methods

Exploring Node.js for the first time, I'm currently tackling a project where I aim to utilize Request for streaming data from one endpoint to another. The objective is to leverage Request for extracting and posting an altered JSON body through a pipe ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...

How can the Request and Response objects be accessed in external Node.js (Express) files?

My project folder structure is as follows : app Controller testController.js Service testInfoService.js testMoreDataService.js config node-modules public index.js routes routes.js Here is some code : routes.js ro ...

"Using AngularJS to fetch data with $http and store it in an

Utilizing $http.get to retrieve data which includes MailID and SubscribedDate. The results are stored in $scope.subscriber. I am interested in extracting an array of all MailID values such as: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...