Filter an array containing nested objects based on dynamically determined properties

I'm working with an array of N objects and need to create a filter using JSON.stringify that dynamically checks multiple properties.

Looking for a solution that is dynamic and doesn't rely on static properties (as shown in the code snippet above).
Any suggestions?

return items.filter(item =>
    JSON.stringify(item.prop1 && item.prop2 & ....)
        .toLowerCase()
        .includes(searchParam)
);

Answer №1

To simplify your object and only keep the desired properties, you'll need to create a function for that:

function selectProperties(object, propertyList) {
  var newObject = {};
  propertyList.forEach(property => {
    newObject[property] = object[property];
  });
  return newObject;
}

With this function, your code will appear as follows:

var propertyList = ['id', 'name', 'date']; // Customize this list with the properties you want to keep
return items.filter(item =>
    JSON.stringify(selectProperties(item, propertyList))
        .toLowerCase()
        .includes(searchParam)
);

Answer №2

 items.filter(item => ["name", "description"].some(attr => item[attr].toLowerCase() === searchParam))

It's not recommended to use JSON.stringify to convert the object into a searchable string because it includes keys in the search process, making it slower compared to directly accessing the necessary keys.

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 best method for showcasing the parsed JSON data in a list view?

Hello, I am new to Android and seeking some guidance. I have two buttons - one for getting JSON data and the other for parsing it. While the first button is working fine, the second one doesn't display the list view as expected. I specifically want t ...

I utilize a Bootstrap modal popup to showcase user alerts across various sections of my website. Each instance of the modal window is triggered from different locations and displays personalized content

<div class="modal" tabindex="-1" role="dialog" id="myModal" data-backdrop="static" data- keyboard="false"> <div class="modal-dialog" role="document"> <div c ...

What causes $(this) to stop functioning post successful execution?

Here are the code snippets I'm currently working with: $(this).removeClass('page larger').addClass('current'); $(this).siblings().removeClass('current').addClass('page larger'); Interestingly, when I try to pl ...

Tips on preventing form submission when clicking on another button within the same form

I created a shopping cart page with functionality to adjust the quantity using JavaScript. I have shared some of the HTML code below, <form action="payment.php" method="post"> <div class="qty__amount"> ...

Sign in a user post-registration with the help of AWS Amplify and React

After a user successfully signs up using the withAuthenticator component, they are immediately logged in upon email confirmation. Is there a way to automatically log them in using a custom sign-in process and the Auth object instead? If so, what steps wo ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

Verifying StartDate and EndDate using AngularJS and Bootstrap Datepicker

My HTML Coding <form name="myForm"> <div class="row"> <div class="col-md-2"> <input data-ng-model="Data.StartDate" type="text" id="startDate" name="startDate" class="form-control" data-da ...

Troubleshooting: Jquery show effects not functioning as expected

Currently, I am facing an issue where I am attempting to display a fixed div using the show function of jQuery. Although the show function itself is working properly, when I try to include an effect from jQuery UI, it does not seem to work as expected. Bot ...

Exploring the concept of self in JavaScript

Exploring the concept of "self" magic, take a peek at this excerpt from nodejs (which is not complete). Socket.prototype.connect = function(options, cb) { ...... var self = this; var pipe = !!options.path; if (this.destroyed || !this._handle) { ...

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

The passport JWT authorization failed, not a single message is being printed to the console

I am currently working on building a login and registration system. I have experience using passport before and had it functioning properly. However, it seems like the npm documentation has been updated since then. I am facing an issue where I cannot even ...

The component 'AddPlaceModal' could not be located in the path '~/components/AddPlaceModal.vue'

Recently, I started incorporating Nuxt for Vue into my projects. In an attempt to enhance my page, I added a new component within the /components folder. However, I encountered a warning during compilation: "export 'AddPlaceModal' was not found ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

Tips on maintaining the Parent menu in a hovered state when the mouse is over the child menu within a Dropdown Menu

I have been working on creating a dropdown menu that functions correctly. However, I am facing an issue where the top menu, when hovered, turns white, but as soon as I move down to the submenus, the top menu reverts back to its original color. Is there a ...

Storing an image as an encoded string in MongoDB: Step-by-step guide

Currently, my goal is to transform an image into a string and store it in MongoDB. Additionally, I would like the ability to decode it at a later time. My approach involves solely using Express, MongoDB, and ReactJS. I specifically do not want to upload t ...

Using Typescript does not generate any errors when indexing an object with brackets

One interesting thing I've noticed about TypeScript is that it allows me to use bracket notation to access an object via index, even when it only has keys. For example: interface testObject { name: string; id: number; } let first: testObject ...

Error found when combining a stopwatch with the react useState hook and setInterval, causing an additional interval to start when the stopwatch

I have implemented a stopwatch feature that includes start and pause buttons. The start button triggers setInterval while the pause button calls clearInterval. Initially, pressing start and then pause works correctly. However, if you press start again afte ...

Minimizing repeated autofocus calls in material-ui's <TextField> component

In the realm of coding with material-ui, when dealing with the <TextField> component, it's important to keep in mind that the solution may actually lie within React itself. Let's paint a scenario where we're crafting a basic login for ...

What steps can I take to ensure that an image does not exceed the size of its parent tag?

Is there a way to ensure that items placed in a container do not exceed the boundaries of the container? I am trying to use my logo as the home button, but when I set the image height and width to 100%, it becomes larger than the nav bar. The CSS for the n ...