Retrieve the key associated with the value array that contains the text being searched for in an AJAX

I have a project where I am handling data to develop a search tool that allows users to search for the name of an individual involved in a legal case. The tool will then display a table with the individual's name, role, and other case details in a specific format:

Case Name Person Role Status
Case 1 John Smith Lawyer (Claimant) Concluded
Case 2 John Smith Expert (Respondent) Suspended

I am using AJAX calls to fetch this data from the API endpoint. An example of the returned object is as follows:

    {
        "id": 3,
        "institution": [
            "Institution X"
        ],
        "party": [
            "Test Investments X.Y.",
            "Czech Republic"
        ],
        ...

To display the role of the searched individual in the table, I need to search through the returned object to find the key associated with the name. For example, in Case 1, John Smith was a lawyer for the Claimant, so I need a function that returns "lawyerClaimant" when searching through the object.

Here is the beginning of the function to request data from the API and display it in the table:

function requestCases() {
        var requestCase = document.getElementById('case-search-input').value;
        var requestConnections = document.getElementById('connections-search-input').value;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', `api/case-list/?first-person=${requestCase}&second-person=${requestConnections}`, true);

        xhr.onload = function() {
            if(this.status == 200) {
                if (requestCase=='' && requestConnections=='') {
                    return null; 
                }
                ...

I have come across variations of functions like this:

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key].includes(value));
}

getKeyByValue(cases[i], requestCase);

However, when I try to use something similar, I encounter a ".includes is not a function" TypeError. Can anyone provide guidance on how to proceed?

Thank you!

Answer №1

An issue arises when certain properties of the object are not arrays, for instance, "id": 3. This prompts an error when attempting to utilize .includes() on them. Thus, it is imperative to verify that the value is indeed an array beforehand:

function findByKey(object, value) {
  return Object.keys(object).find(key => Array.isArray(object[key]) && object[key].includes(value));
}

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

Capturing Ajax Success in Rails

After extensive googling, I have been unable to find my mistake. As a beginner with JS, this may be an easy fix for someone with more experience. Working with Rails 4. I am working on a modal that contains a form and I want to perform certain actions afte ...

jQuery is failing to apply a fade-in effect to a specific row within

I currently have the HTML of a row stored in a variable like so: var newRow = "<tr><td>test</td></tr>" Within my success function, I am attempting to add this: $('.my_table tr:last-child').before(newRow).fadeIn(); Ne ...

span element failed to trigger onload event

I'm encountering a basic issue with my code as a beginner. Below is the HTML snippet: <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html; charset=utf8' /> <scrip ...

Dragging and dropping elements using Jquery to various positions on the screen

I am working on a project with draggable buttons and a droppable textarea. When I drag a button onto the textarea, it displays some code. If I drag another button, the text related to that button is added to the existing code. My query is how can I insert ...

What is preventing the factory from gaining access to the controller?

I have set up a notification factory and passed it inside the controller. However, when I try to assign the factory to the scope within the controller, I am encountering an error. alertsManager MyApp.factory('alertsManager', function() { ...

Combining multiple .php files in a single div

Hey there! I have a piece of code that allows me to load a PHP file into a div. It's currently functional, but I'm facing a challenge where I need to load the next file into the same div. <script type="text/javascript"> $(function() { ...

Steps for incorporating events on Jquery UI button

I have a question about utilizing Jquery UI for the first time. After successfully adding a button using Jquery UI, I am now interested in adding events for when a radio switch is turned on and off. When the radiobox is switched on, I want an alert window ...

Start by retrieving information and then sending properties to a different component

I have been struggling with this issue for more than a week now. Despite thorough reading of the Next.js documentation and extensive online research, I still can't figure out what's wrong. It seems like I must be overlooking something important, ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

What is the best way to modify an image in a column when I hover over a table row that was dynamically inserted using a button function?

Is there a way to dynamically change an image in a column when hovering over a table row that was added through a button function? Here is the current code that I am using, but it does not seem to work as intended when I hover over the row. This function ...

How to invoke a Struts 2 action synchronously using JavaScript

I've been attempting to use JavaScript to make a synchronous call to a Struts 2 action. Despite finding multiple examples, none of them have worked for me. The only method that has worked so far is making an asynchronous call like this: function togg ...

Unable to understand the reason behind why the button is not being displayed

I'm having trouble with my quiz app. I have a button to submit answers and move on to the next question, but whenever I try to place it within the div that contains the quiz, the button disappears. Can someone please help me figure out what's wro ...

Making a Zoom effect using p5.js

I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor) call. However, now I am attempting to implement ...

How to successfully close a jQuery dialog within a user control

My user control has a list view with a hyperlink (LnkDelete) that triggers a jQuery dialog. Here is the javascript code responsible for this functionality: $('#LnkDelete').live('click', function (e) { var page = $(this).at ...

Using Jquery to Insert Numbers Inside Brackets to Selection

I am struggling to calculate the sum of numbers in jQuery for selection fields. Currently, my code looks like this. $(function() { $("select").change(function() { updateTotal(); }); updateTotal(); }); function updateTotal() { ...

Establishing REST parameters for jQuery to consume a web service

Currently, I am utilizing jQuery to consume a custom-built web service that serializes input into JSON and outputs it via jQuery AJAX. I am interested in enhancing the RESTfulness of the service by incorporating URI query string parameters. This would ena ...

Why is the JavaScript code not functioning when the page loads?

Here is the HTML code snippet: <head> <link href="/prop-view.css" media="screen" rel="stylesheet" type="text/css"> <script src="/javascripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type="tex ...

Requesting data asynchronously using AJAX and displaying the filtered results on a webpage using JSON

When I send a request to my node.js server for a .json file containing person information (first name, last name), I want the data to be filtered based on user input. For example: When I request the .json file from the server, it gives me a list of people ...

Using the Greasemonkey browser extension, one can employ the waitForKeyElements utility to trigger a function once a designated element becomes visible on the webpage

(In connection to the question I posted on Stack Overflow). I have been developing a userscript for metal-archives.com, which can be found here. When you navigate to a band page (like this example), you will see the DISCOGRAPHY section and its sub-tabs ...

I am currently developing a program that is displaying a blank page despite my efforts to write

I've been trying to write the code below but it only shows a blank page. var greeting = React.createClass({ render: function() { return ( <div> <h1>Hello</h1> </div> ...