Utilize Lodash to dynamically filter data based on nested filter conditions

To enhance my product data filtering capabilities, I aim to implement multiple dynamic filter conditions. The initial format of my raw data is structured as follows:

[{

 ...,

 "_source": {

  ...,

  "categories": [
   "home",
   "office"
  ],

  ...,

  "attributes": {
    "colors": [
      "Red-White-Blue",
      "Orange-Red-Black"
    ]
  },

  ...,

 }
}]

Subsequently, I possess another dynamic object with key-value pairs that are generated during runtime. The structure of this object is:

{  
   selectedFilters: {
     categories: ["home", "office", "public"],
     colors: ["Red-White-Blue", "Orange-Red-Black", "Blue"],
     ...
   }
}

It is important to note that the existence of certain keys, like the categories array, may vary dynamically. Consequently, the key-value pairs are generated dynamically as well.

My objective is to iterate through all the keys within the selectedFilters object and locate their corresponding values within the raw data arrays.

For instance, if selectedFilters contains categories as home and colors as white, then all products categorized as home with white color should be retrieved from the main product database. If colors has no specified value, then all products categorized as home should be returned, and vice versa. For instance, if color is white and no category is specified, then all products with white color should be retrieved regardless of category.

Is there a method to achieve this task with or without Lodash?

Answer №1

I recently found a solution for handling dynamic keys in searchFilters, which allowed me to successfully filter data from the product dataset.

const filterKeys = Object.keys(this.selectedFilters);

filterKeys.forEach(function(key) {

  let filteredProducts = _.filter(self.products, function(product) {

  let flag = false;
  let searchFilterKey = self.selectedFilters[key];
  searchFilterKey.forEach(function(sKey) {
    let index = product._source[key].indexOf(sKey)
    if (index > 0)
      flag = true;
  })
  if (flag)
    return product;
});

self.filteredProducts = filteredProducts

});

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

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

Avoiding the triggering of jQuery events from child elements

Here is the code snippet I am working with: <html> <head> <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"> </script> </head> <body> <div id=&q ...

Positioning html images to overlap each other without losing the ability to click

Currently, I am facing a challenge with positioning two images over each other. The back image should be at the bottom, while the center image needs to be on top of it. Additionally, there is a requirement for placing a random link (in this case google.com ...

Inserting line breaks in the data retrieved through AJAX

Utilizing ajax to transfer data from a sophisticated custom field wysiwyg editor. Within the markup provided, I am specifically addressing the div with the 'bio' class. However, upon receiving the data, it is consolidated into one large paragraph ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Ace Code Editor: Turn off highlighted line beneath cursor

I am currently utilizing the Ace editor and would like to remove the shadowed line where the cursor is located. Here's an example Even after experimenting with different themes provided by Ace Mode Creator, the shadowed line still persists. Any sug ...

What is the specific table element compatible with Polymer3?

I stumbled upon iron-data-table (), but it relies on bower which is used in Polymer2. However, I am working with npm in Polymer3. Is there a suitable table element or an alternative solution compatible with Polymer3? ...

Steps to display images within a div from a specific directory

Recently, I have encountered a challenge that involves retrieving images from a specific directory, regardless of the number of images present, and then displaying them in a div using an unordered list. I attempted the following code snippet, but unfortuna ...

How to send arrays through JSON?

I have some PHP code: $ids = array(1,2,3); $names = array("cat","elephant","cow"); $originalSettings = array ('ids'=>$ids,'names'=>$names); $jsonSettings = json_encode($originalSettings); echo $jsonSettings; Here ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

Can Moment.js be used to calculate the difference in years and months between two dates?

Currently, I am calculating the difference between two dates in months using this code: _result = Math.abs(moment(date1).diff(moment(date2), 'months')) + 1; This code returns an integer representing the duration in number of months. Now, I woul ...

Exciting jQuery animations and transitions

Is there a way in JavaScript to call function or method names using a string? For example, when writing jQuery code that applies an effect to specific targets, can the effect be dynamic and changeable by the user? I'm hoping for something like jQuer ...

Checking for multiple click events in jQuery

To access the complete code, visit the GitHub Pages link provided below: Link This is how the HTML code appears: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

It is impossible for Javascript to access an input element within a gridview

I have developed an asp.net page that allows a site administrator to select a user as the 'systems chair'. The page displays users in a gridview and includes a column of radio buttons to indicate who the current chair is or to change the assigned ...

Utilizing stored data to display multiple markers on Google Maps with Node, MongoDB, Express, and EJS

I've been working on a project that involves passing values from mongodb to the google maps script in order to display multiple markers. While I've been able to load the map successfully, I'm facing difficulties defining my customers and loo ...