Limit Table Search to Specific Dynamic Key Values in JavaScript ArrayObjects

Currently, I am in the process of developing a customized search feature that involves working with an array of objects.

const data = [{
    name: "Janet McKenly",
    age: 49,
    city: "Baltimore",
    active: "2019-02-15",
    role: "Admin. Assistant"
  },
  {
    name: "Eric Brown",
    age: 23,
    city: "Dallas",
    active: "2020-06-01",
    role: "Janitor"
  },
  {
    name: "Nora Payne",
    age: 41,
    city: "Los Angeles",
    active: "2020-10-02",
    role: "Sales Associate"
  }
]

In addition to this, there is another array which is being generated dynamically and serves as a restriction on the specific parameters allowed for searching purposes.

let searchColumnOnlyArray = ["name", "city", "active"]; // (generated dynamically)

It should be noted that role & age are excluded from being searchable.

The primary objective here is to conduct searches exclusively within the values associated with keys mentioned in the searchColumnOnlyArray.

Although I have successfully implemented filtering by manually inputting a name parameter ["name"], the challenge now lies in adapting to the dynamic nature of searchColumnOnlyArray, which may undergo modifications... The following code snippet illustrates the current method I am utilizing:

searchTable(term: any, data: any) {
   let search = data.filter((indivitem: object) => {
       if(indivitem["name"] === term) {
         return indivitem;
       }
   }
   console.log("searchResults", search);
}

Any suggestions or guidance on how to leverage the searchColumnOnlyArray to exclusively search within the specified keys would be greatly appreciated. Tips on how to refine my filter function to search values based on the set keys in searchColumnOnlyArray would also be valuable.

Answer ā„–1

If you want to filter your data based on specific column values, you can utilize the .some() method within your filter callback function. By using the .some() method, you can loop through each item in your columns array and return a boolean value indicating whether any of the given column values match the search term. If none of the columns pass the test, the .some() method will return false, causing the item to be excluded from the final filtered array:

const data = [ { name: "Janet McKenly", age: 49, city: "Baltimore", active: "2019-02-15", role: "Admin. Assistant" }, { name: "Eric Brown", age: 23, city: "Dallas", active: "2020-06-01", role: "Janitor" }, { name: "Nora Payne", age: 41, city: "Los Angeles", active: "2020-10-02", role: "Sales Associate" } ];

const searchColumnOnlyArray = ["name", "city", "active"];
const term = "Dallas";
const search = data.filter(item =>
  searchColumnOnlyArray.some(col => item[col] === term)
);
console.log("searchResults", search);

Please keep in mind that when using the .filter() method, your callback function should return true or false to determine if an item should be included in the resulting array. Returning the item directly, as shown in your example, is not the correct approach for filtering data.

Answer ā„–2

data.forEach(item => {
   searchColumns.forEach( term => {
       console.log(item[term]);
   });
});

I'm unable to run the code at the moment, but I believe this will work effectively

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

Convert an ArrayList back to a standard array

I'm currently working on a method that needs to return all objects from an array list. I'm not sure if I should even be using an array list for this task. The problem I'm facing is that I need to return an unknown number of objects in a sin ...

Seeking the value of a tab text using Selenium's web driver

Greetings! Currently, I am exploring the integration of selenium webdriver with mocha and node js in order to automate testing for a Single Page Application (SPA). My objective is simple - to locate a specific tab and perform a click action on it. The HTML ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

The <servicename> is inaccessible within an error function in Angular2

I encountered an unusual issue in angular2. While the code below is functioning correctly: loginResult.subscribe( (data) => this.response = data, (err) => this._ajaxService.handleError(err, 'A string to summarize th ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

exploring the ins and outs of creating computed properties in TypeScript

How can I store an object with a dynamically assigned property name in an array, but unsure of how to define the array properly? class Driver { public id: string; public name: string; constructor(id , name) { this.id = id; th ...

Replace the placeholder text with an icon

I am having trouble changing the placeholder text using a function. I am unable to add any additional code to style the text, such as making it bold or adding an icon next to it. When I try to do so, the code is displayed as text instead of being executed. ...

Customizing the initial page layout in Elm

I am new to Elm and I need help with a particular issue. Can someone provide guidance or direct me to a useful resource for solving this problem? The challenge Iā€™m facing involves editing the start page of a website by removing specific elements, as list ...

Personalized cursor that blinks while utilizing window.history.replaceState

While navigating between sub-pages, I utilize the window.history.replaceState method to replace URLs in my web application. However, I have noticed that my custom cursor briefly blinks (replaced by cursor: default) when the current URL is replaced with a n ...

Is there a way to determine when all Angular commands have finished executing through Javascript?

I have been using the following code to determine when my webpage has finished loading, however, it seems like there might be an issue. It appears that the Angular components are not yet executed even when the document.readyState is complete: page.ope ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

Retrieving data from the <script> tag and transferring it to the t-esc tag within Odoo 12

After attempting to retrieve the current coordinates of a location in Odoo, I successfully obtained longitude and latitude data through an alert generated by the following code: <button onclick="getLocation()">Try It</button> ...

Glowing beams of light emitted by point light in three.js

Is there a way to visualize light rays from a point light in a Three.js scene without affecting the entire scene with fog color? var width = $('#g_pre_emo').width(); var scene = new THREE.Scene(); scene.fog = new THREE.Fog(0xffff00, 0, 10); ...

The functionality for navigating the Angular uib-dropdown using the keyboard is currently experiencing issues

I am currently utilizing Angular Bootstrap 2.2.0 in conjunction with Angular 1.5. Despite enabling the keyboard-nav option, I am experiencing issues with keyboard navigation on UIB dropdowns. Below is the snippet of my code: <div class="btn-group" ...

Using Vue components alongside vanilla JavaScript code

I am currently working on integrating Vue.js into an existing project that does not utilize Vue. Unfortunately, I have been unable to find any resources or documentation on how to create a Vue component with an API that can be accessed by external code out ...

Unresolved issue with AngularJS radio button binding

As a beginner in using Angular.js, I encountered an issue with data binding when dealing with radio buttons. The HTML code in question is: <label class="options_box" ng-repeat="item in item_config_list.item_config"> <input type="radio" name ...

JavaScript regular expression for detecting valid characters without repeating a specific character

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi; let s = 'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href'; let m; let res = []; while ((m = rx.exec(s))) { res.push(m[1]); ...

Establishing a pre-selected option in a drop-down menu

I am working on a dropdown list and my goal is to have the default option selected when the page loads <b>Filter Within Months:</b> <select class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change= ...

I encountered a CORS policy error while using React. What steps can I take to effectively manage and resolve this

INDEX.JS import express from "express"; import { APP_PORT } from "./config"; import db from "./database"; import cors from "cors"; import bodyParser from "body-parser"; import Routes from "./routes&quo ...