How can you navigate a JSON product as if it were your own personal database?

I have a JSON file with various file names and extensions:

{
  "COMPONENTS_EXPORT_FILENAME" : "Components.xls",
  "CONTRACT_DETAILS_EXPORT_FILENAME" : "ContractDetails.xls",
  "CONTRACT_LIST_EXPORT_FILENAME" : "Contracts.xls",
  "EQUIPMENTS_EXPORT_FILENAME" : "EquipmentList.xls",
  "FILENAME_PDF_SERVICE_PERFORMANCE_REPORT" : "ServicePerformanceReport.pdf",
  "INVOICES_CONTRACT_LIST_EXPORT_FILENAME" : "ContractInvoices.xls",
  "INVOICES_LIST_EXPORT_FILENAME" : "ServiceInvoice.xls",
  "INVOICES_PSR_LIST_EXPORT_FILENAME" : "PSR_Invoices.xls",
  "MG_REQUEST_TYPE_OPTION_VALUES" : "PMReq:#Preventive Maintenance",
  "OPTIONS_LIST_EXPORT_FILENAME" : "OptionsList.xls"
}

I am trying to implement a search functionality where if the user types 'xls' in a search bar, it should return the matching key-value pairs like this:

OPTIONS_LIST_EXPORT_FILENAME: OptionsList.xls
COMPONENTS_EXPORT_FILENAME : Components.xls
CONTRACT_DETAILS_EXPORT_FILENAME : ContractDetails.xls
CONTRACT_LIST_EXPORT_FILENAME : Contracts.xls
EQUIPMENTS_EXPORT_FILENAME" : EquipmentList.xls

Currently, I am using JSON.parse and JSON.stringify, but I'm facing issues as I have to specify keys like

json_file.CONTRACT_LIST_EXPORT_FILENAME
which returns lowercase values such as contracts.xls. Can you suggest a workaround for this problem?

After taking advice from @nikhil, I have updated my code as follows:


var data = {
   "COMPONENTS_EXPORT_FILENAME" : "Components.xls",
   "CONTRACT_DETAILS_EXPORT_FILENAME" : "ContractDetails.xls",
   "CONTRACT_LIST_EXPORT_FILENAME" : "Contracts.xls",
   "EQUIPMENTS_EXPORT_FILENAME" : "EquipmentList.xls",
  "FILENAME_PDF_SERVICE_PERFORMANCE_REPORT" : 
  "ServicePerformanceReport.pdf",
 "INVOICES_CONTRACT_LIST_EXPORT_FILENAME" : "ContractInvoices.xls",
 "INVOICES_LIST_EXPORT_FILENAME" : "ServiceInvoice.xls",
 "INVOICES_PSR_LIST_EXPORT_FILENAME" : "PSR_Invoices.xls",
 "MG_REQUEST_TYPE_OPTION_VALUES" : "PMReq:#Preventive Maintenance",
 "OPTIONS_LIST_EXPORT_FILENAME" : "OptionsList.xls"
 };


function getTextInput() {
        var e = document.getElementById("myText").value;
        document.getElementById("txt").innerHTML = e;
        return e;
        }

function search(data, searchKey) {
var results = [];

Object.entries(data).forEach(([key, value]) => {
  if (key.toLowerCase().includes(searchKey.toLowerCase()) ||
  value.toLowerCase().includes(searchKey.toLowerCase())) {
  results.push({
    [key]: [value]
  });
 }
});

 for(var i in results)
{
  document.write(i + "=" + results[i] + '<br>');
}


}
search(data,getTextInput);

Answer №1

If you want to filter entries in an object based on a specific search string, you can leverage the power of Object.entries() along with Array.filter().

var data = {
  "COMPONENTS_EXPORT_FILENAME" : "Components.xls",
  "CONTRACT_DETAILS_EXPORT_FILENAME" : "ContractDetails.xls",
  "CONTRACT_LIST_EXPORT_FILENAME" : "Contracts.xls",
  "EQUIPMENTS_EXPORT_FILENAME" : "EquipmentList.xls",
  "FILENAME_PDF_SERVICE_PERFORMANCE_REPORT" : "ServicePerformanceReport.pdf",
  "INVOICES_CONTRACT_LIST_EXPORT_FILENAME" : "ContractInvoices.xls",
  "INVOICES_LIST_EXPORT_FILENAME" : "ServiceInvoice.xls",
  "INVOICES_PSR_LIST_EXPORT_FILENAME" : "PSR_Invoices.xls",
  "MG_REQUEST_TYPE_OPTION_VALUES" : "PMReq:#Preventive Maintenance",
  "OPTIONS_LIST_EXPORT_FILENAME" : "OptionsList.xls"
};


function search(data, searchKey) {
  return Object.entries(data).filter(([key, value]) => {
    return key.toLowerCase().includes(searchKey.toLowerCase()) ||
      value.toLowerCase().includes(searchKey.toLowerCase());
  });
}

console.log(search(data, ".xls"));

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

What is the most efficient method for exporting Express route functions for promise chaining?

Currently, I am in the process of refactoring an API route to utilize ES6 promises instead of callbacks, so as to avoid callback hell. Upon successful conversion to a promise chain, my intention was to extract the .then() functions into a separate file fo ...

Creating a visual representation of the information stored in my JSON data file using a Quasar table

As a VueJS student, I'm struggling to display the distances from my JSON file in a table. What is the best way to retrieve and show all the distance data for "5" and "10" by both walking and driving? Should I use this code: this.concurrentsRows = JSO ...

Javascript function functioning properly with certain divs but experiencing issues with other divs

Let me briefly explain the functionality here: I have a piece of HTML code with multiple categories, two of which are displayed below (usually there are five). The sections include registration and lobby. In each category, there are predefined responses th ...

The AngularJS script is throwing an error that states "ReferenceError: Invalid left-hand side in assignment

While attempting to establish a connection with a webservice, I made an attempt using AngularJS $http option. However, when testing it out, I encountered an error in the console of my Chrome browser: ReferenceError Invalid left-hand side in assignment. Des ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

The issue of Spring's @RequestBody failing to map to a custom Object

My custom Object, named ExampleObject, contains a org.json.JSONObject as a mongo query. public class ExampleObject { private JSONObject query; private String[] projections; private Number limit; // Constructors, getters and setters } In my REST contro ...

The response parser in Angular 7 is failing to function correctly

Hey, I recently updated my Angular from version 4.4 to the latest 7 and after encountering several errors, I was able to get my service up and running. However, I'm facing an issue with my output parser function which is supposed to parse the login re ...

Exports for Express Router Module/Functions

I am currently working on exporting a function and an express router from the same file. The function is intended to verify certificates, while the route is meant to be mounted on my main class for other routes to use. I want to encapsulate both functional ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...

React Sortable JS is causing the bootstrap grid style to disappear

As I work on developing a straightforward React application, my goal is to integrate React Sortable Js into my Bootstrap grid layout. However, when I enclose within <ReactSortable>, the grid layout no longer displays two boxes side by side in two ro ...

Changing the selected value in a dropdown menu when the first dropdown is selected

Currently, I am facing an issue where changing the value of the first dropdown also changes the value of the second dropdown. How can I resolve this issue? I want to ensure that when I change the value of the first dropdown, the second dropdown does not i ...

Requesting data from the application to the MongoDB database is currently malfunction

Currently, I'm utilizing Express and passport to develop an application. Everything has been going smoothly so far, but I've encountered a problem when attempting to retrieve data from my mongo database. Strangely enough, I am able to successfull ...

What is the best way to choose and showcase data from a JSON array that includes nested sub arrays?

My data has been encoded using JSON echo json_encode($something) This is what I retrieved from my MongoDB database: [ { "_id":{ "$id":"535f6dc8b8082fd3f80dea0f"}, "val":"mukund", "value":"Lost in the woods" } ] I am look ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

Creating an HTML drop-down menu for selecting a vehicle

I am looking to incorporate two drop down menus on my website. One for selecting car brands and the other for choosing specific car models. I have successfully set up the drop down menu for car brands, but it currently only displays four options: Maruti Sw ...

What methods can I employ within an AngularJS controller to retrieve data from Google App Engine instead of solely relying on a JSON file?

As a newcomer to web development, I have been experimenting with retrieving data from a Google App Engine datastore and selectively displaying it on a webpage using AngularJS. While I have successfully integrated Angular with a JSON file and posted the con ...

generate a listing based on an HTTP query

Here is the code snippet from my controller : @RequestMapping("/allU") public List<Utilisateur> AllU() { return UtilisateurRepo.findAll(); } When I try to access this data in my AngularJS code like this : $scope.list=$http.ge ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

Issues with JSON button click on login API web server

I have been working on developing a login app that connects to a web server API. Everything runs smoothly when I compile the files in Android Studio. However, upon running the app on either the emulator or a real Android device, I encounter an issue where ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...