Exploring an array for multiple values using match() function

My goal is to retrieve the object that contains a value matching the searched text. Currently, I achieve this using the return match function. However, I am facing difficulties in testing for numbers within the array. The current implementation only works if I input the type or the name.

For instance, if I input '2', the expected output should be [{"type":"ABe 8/12", "name":"ZTZ","numbers":["1", "2", "3", "4", "7"]}]

The JSON data:

[
    {"type":"ABe 8/12", "name":"ZTZ","numbers":["1", "2", "3", "4", "7"]},
    {"type":"ABe 4/16", "name":"STZ","numbers":["5", "6", "8", "9", "12"]},
    {"type":"ABe 4/16", "name":"RTZ", "numbers":["10", "11", "13", "14", "15"]},
    {"type":"Test", "name":"RTZ", "numbers":["16", "17", "18", "19", "20"]}
]

The provided Javascript code fetches the data from the JSON file and filters it based on the search text entered by the user. It then logs the matches to the console.

If anyone has an alternative method to achieve this other than using the return match function, please let me know.

Answer №1

Here is my idea, take a look at the comments below.

const search = document.getElementById('search');
const searchData = async searchText => {
    const res = await fetch('https://cmd-golem.github.io/json/test.json');
    const resJson = await res.json();
    const regex = new RegExp(`^${searchText}`, 'gi'); // Ensuring it's outside the filter function.
    // Recursive function.
    const found = data => (Array.isArray(data) ? data.find(found) : data.match(regex));
    let matches = resJson.filter(data => (found(data.type) || found(data.name) || found(data.numbers)));
    console.log(matches);
};
search.addEventListener('input', () => searchData(search.value));
<input id="search" type="text" placeholder="Search">

Answer №2

It seems like you were heading in the right direction. To search for specific quoted text, consider using code similar to this:

let data = [
  {"type":"ABe 8/12", "name":"ZTZ","numbers":["1", "2", "3", "4", "7"]},
  {"type":"ABe 4/16", "name":"STZ","numbers":["5", "6", "8", "9", "12"]},
  {"type":"ABe 4/16", "name":"RTZ", "numbers":["10", "11", "13", "14", "15"]},
  {"type":"Test", "name":"RTZ", "numbers":["16", "17", "18", "19", "20"]}
];

let filter = "2";
let pattern = new RegExp(`"${filter}"`);
let filtered = data.filter((d) => pattern.test(JSON.stringify(d)));

console.log(filtered);

By using stringify to convert each item into a string, and then employing a RexExp test, you can successfully check for any matches of filter within that string.

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 can we verify if a function passed through mapDispatchToProps was invoked using RTL when there are no observable changes in the UI?

Is it possible to verify that a function passed in mapStateToProps was successfully called with RTL, even when there are no visible changes in the user interface? ...

When working with multiple states in React, the toggle does not update on click when using setState

As a beginner in React JS, I have been learning and experimenting with state management. Initially, I successfully used setState to change the state. However, I encountered an issue when attempting to work with multiple states simultaneously – it didn&ap ...

Name is the only piece of information that does not get stored in the

I'm struggling with my AJAX script that sends data to the database. Everything goes into the database except for $name and $n. My code is too long to share here, but I would really appreciate some help as my final year project submission deadline is a ...

Using php variable to pass data to jquery and dynamically populate content in jquery dialog

I am facing challenges trying to dynamically display MySQL/PHP query data in a jQuery dialog. Essentially, I have an HTML table with MySQL results. Each table row has an icon next to its result inside an anchor tag with the corresponding MySQL ID. echo &a ...

Mapping object data within an object in React: A step-by-step guide

Within my React project, I am retrieving data from a JSON source like so: https://i.sstatic.net/fEZFL.jpg The simplified JSON data appears as: const listData = [ { "_id": "abscdf456", "bucket": { code: "videos" }, "contents": [{}, {} ...

Adding a file filter in Kendo v2016 is a simple process that can greatly enhance

I'm exploring how to implement a file filter in Kendo.Mvc.UI.FileUpload. I've come across some examples online that utilize a method called 'select', but it seems that the current version of Kendo I'm using doesn't have this m ...

Retrieving a boolean value from a function that includes an asynchronous AJAX request

In my calendar application, I am working with an array of dates: <div v-for="date in dates">{{ date }}</div> I want to apply a conditional class based on the outcome of an isWeekend() method that involves making an API call: <div v-for="d ...

Authenticating the Gmail API using a specified user ID

Is there a way to manually input email and password for authentication in the Gmail API without using the default Google popup? I need users to enter their login credentials directly, but I can't figure out how to do it. The code I am currently using ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Tips for managing white spaces in field names within a JSON file when constructing an Athena table

One issue I encountered is that my JSON file contains field names with spaces, such as "Customer ID". The JSON file is stored in an S3 bucket. When attempting to create an Athena table using this JSON file, it results in an error due to the presence of s ...

After the form is successfully submitted, you can remove the required attribute

Upon clicking the submit button of a form, an input box is highlighted with a red border if empty. After successful jQuery AJAX form submission, a message "data submitted" is displayed and the form is reset causing all input fields to be highlighted in red ...

I'm trying to figure out how to switch the Heroes array to the res array while utilizing the react useState hook. It's been successful in my past projects, but for some reason,

const [Heroes, setHeroes] = useState([]) useEffect(() => { API.findFavorites().then((res) => { console.log(res) setHeroes([...Heroes, res]); console.log(Heroes) }) }, []); I am struggling ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

Concealing the Footer on Mobile Websites in Muse UI When the Keyboard Appears

In this project, I am using vue.js along with muse.ui and only incorporating JavaScript and CSS without the jQuery library. Currently, the footer position always ends up on top of the keyboard whenever an input field is focused. Is there a way to ensure th ...

Unexpected behavior: jQuery events failing to execute while triggering the 'change' event with fireEvent

Issue seen in IE7-8. Here's a simple illustration: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <script type="text/javas ...

Retrieve Textures From an Assortment

Greetings to all the readers here! I am in the process of developing a website where I want to implement a feature that allows me to scroll through "cards" arranged in a single line, visible from an isometric side view. I have managed to set up the scene ...

Incorporate Voice Recognition into an HTML document

Specifically designed for mobile devices: I am looking to implement a feature on my mobile site where a button allows users to speak into their phones. After they finish talking, a random mp3 file will play. Would it be feasible to achieve this using JQue ...

Designing a carousel-style menu list with navigation buttons for moving forward and backward

I'm running into some trouble while attempting to create a carousel. Firstly, the issue I am facing is that when you continuously click on the Next button, the function keeps working even after reaching the last item. I'm not sure how to make th ...

Exploring the Power of AngularJS' $resource with JAX-RS Integration

Recently, I developed a small web application using AngularJS, JAX-RS, and Hibernate. While I am able to retrieve objects of my type 'Plugin' successfully, I am facing issues with saving them. Upon inspecting the object on the server, I noticed t ...

A guide to gathering a variety of data types for an array in Node.js

As a JavaScript beginner, I am on a mission to enhance my skills by solving online judge problems. However, I have hit a roadblock with a specific issue. The problem requires me to take input from the user in the form of an integer and a string in one go, ...