Search through an array of objects that contains nested arrays of objects with various property names and values

I have an Array of objects structured like this:

[{
    property1: 'test',
    property2: 'test',
    filter: [{
        fil1: 1,
        fil2: 2,
        fil3: 3
      },
      {
        fil1: 56,
        fil2: 3,
        fil3: 34
      },
      {
        fil1: 23,
        fil2: 88,
        fil3: 6
      }
    ]
  },
  {
    property1: 'test2',
    property2: 'test2',
    filter: [{
        fil1: 44,
        fil2: 5,
        fil3: 99
      },
      {
        fil1: 333,
        fil2: 7,
        fil3: 888
      },
      {
        fil1: 10,
        fil2: 5,
        fil3: 688
      }
    ]
  }
]

Within the array, there are two objects, each containing nested arrays with additional objects. I am seeking to find the main object when searching for specific properties within the nested objects.

For example, if I search for fil1: 56, fil2:3 , I need to retrieve the first main object that matches these criteria. However, it's important to note that the property names inside the nested objects may vary and sometimes I might need to conduct a search based on one property or multiple properties. I have a search object defined as follows:

{
  fil2: 2,
  fil3: 3
}

By inputting this search object, I would expect to retrieve the first main object in the array that meets the specified criteria.

Answer №1

data.find((item) => item.filters.some((item_filter) => !Object.entries(searchParams).some(([key, value]) => item_filter[key] != value)));

In this code snippet, data represents an array of objects that can be searched through, and searchParams is the search criteria object. It will return the first matching object from the data array based on the provided search parameters.

This method is flexible and can handle any number of keys within the filter array element or in the search object.

For example:

{
    filterKey1: 5,
    filterKey2: 5,
    filterKey3: 686,
    filterKey4: 686,
    search_by_this_key: 34,
    ...
}

When dealing with large datasets, filtering arrays client-side may impact performance. In such cases, consider implementing a backend solution for better efficiency.

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

Creating a new array by elegantly extracting elements from an existing array

I'm trying to improve the efficiency and flexibility of constructing the array final_array_transpose using elements from another array, imb_data (which currently contains 5 elements but could potentially have any number). The code snippet below shows ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

Can OR be utilized within a find operation?

I am currently developing a social media platform similar to Facebook using Express and MongoDB. One of the features I'm working on is adding friends to user profiles. When a user clicks on a button that says "Send Friend Request" on another user&apos ...

Encountering an issue with inability to resolve the 'react-navigation-stack' module. Still seeking a solution to this problem

Having trouble with my react navigation in react native. I've already added npm react-navigation-stack and also npm install --save react-native-gesture-handler react-native-reanimated react-native-screens. The error message I'm getting is: Unab ...

Rendering issues arise in the app when utilizing browserHistory instead of hashHistory with React Router

I have integrated React Router into my current project in the following way: const store = Redux.createStore(bomlerApp); const App = React.createClass({ render() { return ( React.createElement('div', null, ...

Problem with updating an Html.TextBoxFor based on the value of another one

I have been trying to implement a basic jQuery functionality that involves changing the text in one textbox to be half of the numeric value entered in another textbox. Below is the script I am using: <script> $(document).ready(function () { $(& ...

Testing reactive streams with marble diagrams and functions

Upon returning an object from the Observable, one of its properties is a function. Even after assigning an empty function and emitting the object, the expectation using toBeObservable fails due to a non-deep match. For testing purposes, I am utilizing r ...

The function URL.createObjectURL() is failing to work across all browsers

Despite my efforts, I'm feeling tired as none of the solutions seem to work for me. Here is the HTTP call in Angular that I am struggling with: $http({ method: 'GET', url: API_URL + 'v1/file/' + candidateId + '/download& ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

Resource loading unsuccessful: server returned a 401 status code for React webpage

( ) I'm currently working on a website dedicated to searching for GitHub users as part of my React course. However, I seem to be facing an issue with the website not fetching the response properly, possibly due to an Axios error. When searching for ...

Converting a JavaScript object into JSON format

I am currently working on serializing a JavaScript object to JSON. Here is the code I have written so far: var info = {}; ... $.each(data, function (key, value) { info["name"] = value.name; info["id"] = value.id; ...

Having trouble identifying the memory leak within the linked lists function, specifically detecting "16 bytes in 1 block are undeniably lost in loss record 1 of 1"

I have been studying C and implemented several functions to manipulate linked lists. However, I am encountering a memory leak issue which I suspect is related to the reassignment of node* list in lines 28 and 29. I am seeking a solution to resolve this pro ...

Utilizing Next.js to dynamically update data within a div element upon

I have a table set up to display data and I want to transfer the row data into a div when the user clicks on a table row: Currently, I can successfully get the data onclick: const handleClick = (rowData) => { console.log(rowData); } However, I am ...

The Power of ReactJS Spread Syntax

Currently working with React. In the state, I have an array of objects. this.state = { team: [{ name:'Bob', number:23 }, { name:'Jim', number:43 }] } My issue arises when attempting to create a copy of the arr ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

Automatically update the div every few seconds and pause when it has loaded successfully

I am facing a challenge in creating a div that refreshes automatically every 10 seconds, but stops when it successfully loads. Here is the jQuery script I have developed: <script type="text/javascript"> $(document).ready(function(){ var j = jQuer ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

Aligning the second heading alongside pictures and a lightbox

My issue is that I am struggling to center the "See More" link directly under each title link. Currently, it is pushed to the right and I can't seem to find a solution. Any help with this problem would be greatly appreciated. I attempted using display ...

Transition the object in smoothly after the slide has changed

How can I make the h4 tags fade in after the divs slide into view, while also adding the class "current" to each visible slide? Check out the example on JSFiddle here. <div class="slider"> <div class="slides"> <div class="slide ...

Best method to incorporate JSON array from WebService into a Dataframe

I have a column titled 'code' that I need to send to a web service in order to update two specific fields (dfMRD1['Cache_Ticker'] and dfMRD1['Cache_Product']) with data retrieved from the JSON response, specifically the values ...