Having trouble retrieving an object within a function by using Array.filter in Vanilla JavaScript

I have been working on creating a search functionality using Vanilla JavaScript. While the code works fine in the Browser's web console, I am facing issues with outputting the object once it is wrapped in the function.

The process involves having the user input a search term in an HTML form. The form then stores this value in a variable called _searchInput, which is saved in session storage. When I check session storage in the web console, it shows the stored variable with the expected value. However, upon trying to return the _results variable, it seems to be returning an empty array.

For clarification, the inputValue(); function is responsible for checking if the user has entered a value and then calling searchFunc(); if the search field is not empty.

The HTML Form:

<form name="entryForm">
<input id="searchInput" type="text" label="Search" onclick="this.value = '' " />
<button id="searchBtn" onclick="inputValue();">Search</button>
<p id="response">I'm the value</p>
</form><br><br>

The Object Array:

const allInvItems = [{
"ProdId": "1",
"InvItemName": "T-shirt",
"GinNum": "640041 - T-shirt",
"QtyServUnit": "1",
"QtyCountUnit": "1",
"PurchUnit": "EA - Each",
"CountUnit": "EA - Each",
"SellUnit": "EA - Each",
"CountFrequency": "D - Daily",
"StandCost": "10.6049"
 }, 
 { 
 "ProdId": "2",
 "InvItemName": "Shorts",
 "GinNum": "75043011 - Shorts",
 "QtyServUnit": "8",
 "QtyCountUnit": "1",
 "PurchUnit": "PK - Pack",
 "CountUnit": "EA - Each",
 "SellUnit": "EA - Each",
 "CountFrequency": "D - Daily",
 "StandCost": "2.6049"
 }];    

The Search Function: Here is where I am facing difficulty:

function searchFunc() {
const storedInput = sessionStorage.getItem('_searchInput').value;

let _results = allInvItems.filter(function(obj) {
return obj.InvItemName == storedInput;
});

}

I am expecting the function to filter out all objects except the one stored in the variable captured.

Answer №1

You seem to be incorrectly accessing the key value "_searchInput" in the sessionStorage. To access the key value in sessionStorage, you should use the code

sessionStorage.getItem('_searchInput')
.

const allInvItems = [{
    "ProdId": "1",
    "InvItemName": "T-shirt",
    "GinNum": "640041 - T-shirt",
    "QtyServUnit": "1",
    "QtyCountUnit": "1",
    "PurchUnit": "EA - Each",
    "CountUnit": "EA - Each",
    "SellUnit": "EA - Each",
    "CountFrequency": "D - Daily",
    "StandCost": "10.6049"
  },
  {
    "ProdId": "2",
    "InvItemName": "Shorts",
    "GinNum": "75043011 - Shorts",
    "QtyServUnit": "8",
    "QtyCountUnit": "1",
    "PurchUnit": "PK - Pack",
    "CountUnit": "EA - Each",
    "SellUnit": "EA - Each",
    "CountFrequency": "D - Daily",
    "StandCost": "2.6049"

  }
];

sessionStorage.setItem('_searchInput', 'T-shirt');
const storedInput = sessionStorage.getItem('_searchInput');

const output = allInvItems.filter(({
  InvItemName
}) => InvItemName === storedInput);
console.log(output);

Note - Make sure to run the code in your web browser.

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

How to update a boolean value in a JSON object using AngularJS?

Trying to modify a boolean value when a user clicks on a JSON-populated table row. Here's an example of the setup... $scope.prices = { "Prices": [ { "Code": "edl", "Selected": false }, { "Code": "ead", "Sel ...

The defaultLocale setting in Next.js i18n is failing to retain the default language

I am currently working on setting my default language in Next.js i18n, but I keep encountering a problem where "En" is always set as the default language, acting as a fallback. Additionally, I am receiving this error message: Error: [@formatjs/intl Erro ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...

Having trouble creating a PDF from HTML

Having trouble with generating PDFs using various libraries as I keep encountering the following error: Fatal Error: spawn UNKNOWN The code snippet looks like this: mammoth.convertToHtml({ path: './backend/common/template.docx' } ...

Showing all steps in introJS allows for a comprehensive walkthrough of the user interface

Can all the introJS step numbers be displayed simultaneously to show all areas of the page with explanations, without highlighting their associated elements or tooltips? Could these numbers be made clickable so that users can choose to view an explanatio ...

Update the default window location when the Browse button is clicked

When a user clicks on the browse button on our webpage to upload a file, I want to change the window location. Currently, when the button is clicked, a window pops up defaulting to "My Documents". However, I would like to change this so that when the user ...

Deselect a checkbox by selecting a radio button with just Javascript code

Hey there! I'm currently delving into the world of pure JavaScript and could really use some guidance on a particular issue. Here's what I'm aiming to accomplish: I'd like to design a checkbox that triggers the opening of a window whe ...

Node.js encountered an issue: Dependency 'mime-types/node_modules/mime-db' cannot be located

Recently, I followed a tutorial on creating a CRUD App with Nodejs and MongoDB. The project was completed successfully and everything was working fine. However, when I attempted to move all the files and folders to a new directory, disaster struck. Now, w ...

Different ways to streamline the validation process for multiple input fields in a form using Vue 3

Within my application, there lies a form consisting of numerous input fields. These text input fields are displayed based on the selection made via radio buttons. I am currently validating these input fields by specifying the field name and its correspondi ...

The unique identifier for retrieving an object from the database is dynamic and subject to change with each

Click here for image description I am currently building an app using Express and Mongoose MongoDB. However, when I try to access /musics/:id to go to the details page, the app redirects me to the correct page but crashes because the id is being changed. ...

Transform jQuery code into vanilla JavaScript

I'm struggling with converting this part of code from jQuery to plain JavaScript. I've documented everything in a JSFiddle as an illustration. The following is the script: $(".button").click(function () { $pageID = $(this).attr('name& ...

Differences Between Vuetify Breakpoints and CSS Helper Classes

As I browse through the Vuetify documentation and various code snippets on the web, I often come across examples that mention using either a Vuetify breakpoint or a CSS helper class to make an element responsive to screen size changes. Is there a preferre ...

What is the method to have VIM recognize backticks as quotes?

Currently working in TypeScript, I am hoping to utilize commands such as ciq for modifying the inner content of a template literal. However, it appears that the q component of the command only recognizes single and double quotation marks as acceptable ch ...

organized information on operations

After retrieving a dataset (lst) from a mysql table, I utilize a datrangeinput to apply a filter. dateRangeInput("daterange", "Date Range", start = min(lst$Record_Date), end = max(lst$Record_Date)) observeEvent(input$daterange, { st <- input$datera ...

The modifications made to a bound value in AngularJS directives do not propagate to the outside components

I've been experimenting with bound variables inside directives, but I'm facing an issue where the view doesn't seem to refresh. Despite the model updating correctly (as seen in the console log) and calling $apply(), the view remains unchange ...

Embedding a Javascript variable within another variable

I have created a variable out of a cookie. var exiturl = readCookie("exiturl"); Now, I have an exit popup script that usually redirects to . Here is how the script looks: var exitsplashpage = 'http://myexitpage.com' ; I would like to replace ...

The modal is functioning perfectly with the initial row in the table

Is there anyone who can help me fix this issue? I've spent a lot of time trying different solutions, but none of them seem to work. I'm using a tailwindcss template for the modal and JavaScript to show or hide it. I'm having trouble findin ...

How to select the final td element in every row using JQuery or JavaScript, excluding those with a specific class

I am looking for a solution with my HTML table structure: <table> <tbody> <tr> <td>1</td> <td>2</td> <td class="treegrid-hide-column">3</td> < ...

Tips for resolving the issue: "Encountered error loading module script..." in Angular 8 and Electron 5

I have been working on developing an Electron 5 app using Angular 8. Despite following numerous online tutorials, I keep encountering the same error. Initially, I set up a new project and ran ng serve --open, which successfully displayed the default angul ...

Bootstrap - Input fields not following grid constraints

I have scoured the internet for answers to my question and haven't found anything useful, not even in previous posts on this forum. Currently, I am working on a website for internal company use and tinkering with it at home. However, I seem to be fac ...