Searching through all objects in an array by specifying a field set in JavaScript

How can I efficiently search through an array of objects by specifying the fields to search within a function call and filtering out specific values? For example:

const src = [ { id:1, name: "name1", age: 25}, { id: 2, name: "name2", age: 33} ]

If I only want to search for values in the name and age fields while excluding the id field, how can this be achieved in code?

function contains(text, subStr) {
  return text.includes(subStr);
}

const searchInData = (searchString, searchData, fieldsForSearch) => {
  const keyword = searchString.toLocaleLowerCase();
  let filteredData = searchData;
  if (keyword) {
    filteredData = searchData?.filter((item) => {
      const { ...fields } = item;
      return Object.keys(fields).some(key => fieldsForSearch.includes(key) && contains(fields[key], keyword));
    });
  }
  return filteredData;
};

Is it possible to pass in an array of field names to limit the search to only those specified fields? Like so,

searchInData(searchString, searchData, ['name', 'age'])

Answer №1

To search for a specific keyword within an object's properties, you can iterate through the keys provided in the third argument and check if any of the item's properties contain that keyword. One way to achieve this is by using the some method:

function findKeywordInData(keyword, data, properties) {
    const searchKey = keyword.toLocaleLowerCase();
    
    // If no properties are specified, search through all properties
    if (!properties) {
        return data?.filter((item) =>
            Object.values(item).some(value => String(value).includes(searchKey))
        );
    }
    
    // If properties are specified, only search through those defined properties
    return data?.filter((item) =>
        properties.some(prop => Object.hasOwnProperty(item, prop) 
                               && String(item[prop]).includes(searchKey))
    );
};

// Example usage
const data = [ { id:1, name: "name1", age: 25}, { id: 2, name: "name2", age: 33} ];

console.log(findKeywordInData("name", data, ["id", "age"]).length); // 0
console.log(findKeywordInData("3", data, ["id", "name"]).length); // 0
console.log(findKeywordInData("3", data, ["age", "name"]).length); // 1
console.log(findKeywordInData("2", data, ["age", "name"]).length); // 2
console.log(findKeywordInData("u", data, ["nonexisting key"]).length); // 0
console.log(findKeywordInData("1", data).length); // 1

Answer №2

I came up with a solution that should meet your requirements:

const data = [ { id:1, name: "name1", age: 25}, { id: 2, name: "name2", age: 33} ]

function extractFields(objArr, fields) {
    const result = objArr.reduce((acc, cur) => {
      fields.forEach(field => {
        if (cur[field]) {
          acc.push({[field]: cur[field]});
        }
      });
      
      return acc;
    }, []);
    
    return result;
}

let extractedData = extractFields(['name', 'age'], data);

console.log(extractedData);

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

Managing a variety of PHP responses using AJAX

I am currently in the process of designing PHP pages for form processing. On these pages, I aim to redirect if the result is successful or display an error message in case of any errors. The structure of the pages is as follows: $arg = $_POST["arg"]; if ( ...

Exploring the functionality of React Signals with arrays

My goal is to utilize Signals (@preact/signals-react) in order to minimize re-rendering when dealing with large data objects. Specifically, I am fetching objects from a network request that tend to change frequently due to live updates. For direct propert ...

Locate the value in an array using a specific string identifier

Below is the array I am currently working with: $items = array( "Rifle" => "rifle", "SMG" => "smg", "Knife" => "knife", "Sticker" => "sticker", "Container" => "case", "Key" => "key", "Shotgun" => "heavy", ...

The Nodejs code snippet successfully allows adding items to the cart, however, a problem arises when adding multiple quantities of similar items individually

Cart functionality is working for initially adding new items, but then each item's quantity is added individually from other similar items? // Logic for handling cart addition // router.post("/", verifyToken, async (req, res) => { let o ...

What is the best way to incorporate all CSS files from node_modules into the css-loader build process?

I am attempting to consolidate all the CSS files located in the node_modules directory into a single file. The configuration for my Webpack setup is as shown below: { // node_modules css in /node_modules/**/*.css test: /\.css$/, include: ...

The native javascript modal fails to appear

I'm attempting to implement the functionality from this Codepen demo into my project. I've copied over the HTML, CSS, and JavaScript code: <!DOCTYPE HTML> <html> <head> <script> var dialog = docume ...

Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: f ...

The effectiveness of recursion in asynchronous function calls within AngularJS

My task involves creating a JSON output in tree structure from recursive async calls. The code I have developed for this purpose is detailed below: $scope.processTree = function (mData, callback) { _processTree.getWebCollection( ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Dynamic Column Placement in Tabulator with AutoColumns and AJAX Integration

Hey there, I'm currently working on incorporating the autoColumns feature in Tabulator using data retrieved via AJAX. My aim is to dynamically add column definition information based on each column's requirements, like filters, sorting, etc. Desp ...

The JSON output containing a <br /> tag (escaped) was not properly interpreted by the browser

I encountered an issue with a JSON file that looks like this: [ { "titel": "Das \"Hexenbödele\" bei Lengstein", "vorspann": "Sage vom Ritten, übertragen von P. Beda Weber. Im Wald oberhalb von Lengstein und von diesem Ort nicht weit ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

Displaying 'N/A' in the chart if the data is missing

I have a chart that displays data, but when data does not exist it shows "undefined%". https://i.sstatic.net/Fm3Tl.png Is there a way to remove the "undefined%" and simply display nothing on the graph if no data exists? Here is the code snippet: import { ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

ways to verify ng-if post modification occurrence

Currently, my project is utilizing Angular 6. In the code, there is a div element with *ng-if="edited" as shown below: <div *ngIf="edited"> {{langText}} </div> Initially, when the page loads, edited is set to false and the div is not vis ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code. export class UsertableComponent { dataSource: MatTableDataSource<TrialUser> createTableFromServer = (data: TrialUsers[], ...

Dealing with Errors in Express 4

After reviewing several posts, I am still confused about how to handle errors. Here is a snippet of my middleware: // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status ...

The feature for favoriting or unfavorite a post is currently not functioning correctly on the frontend (react) side

I have been working on a social media website project for practice, and I successfully implemented the liking and disliking posts feature. However, I encountered an issue where when I like a post and the icon changes to a filled icon, upon refreshing the p ...

Refresh the three.js Raycaster when the window size changes

Currently, I am implementing a ray caster to choose objects within my three.js scene. The specific objects I am working with are box geometries shaped like flooring. After a successful selection of an object, I encountered an issue where resizing the wind ...