Extract all objects from an array where a specific field contains an array

 data:[
        {
           id:1,
           tags:['TagA','TagB','TagC']
         },
         {
           id:2,
           tags:['TagB','TagD']
         },
         {
            id:3,
            tags:['tagE','tagC']
         }
      ]

filterCondition:{tags:['TagA','TagB']}

Expected Output: [
                   {
                     id:1,
                     tags:['TagA','TagB','TagC']
                   },
                   {
                     id:2,
                     tags:['TagB','TagD']
                   }
                 ]

Is there a potential method in typescript to achieve the desired result using the filter function? When the 'tags' field is not an array, it works fine. However, when it's within an array, the code does not produce the expected output.

I have attempted a solution but encountered failures:

   data.filter(o => Object.keys(filterCondition).every(k => filterCondition[k].some(f => o[k] === f)));

Answer №1

Utilize the filter method along with includes

const items = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];
      
const filterItems = tag => items.filter(item => tag.some(t => item.tags.includes(t)));

console.log(filterItems(['TagA', 'TagB']));

Minor adjustment in the conditional array form:

    let filterArray={tags:['TagA','TagB']}

    const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];

    output= data.filter(o => Object.keys(filterArray).every(d => filterArray[d].some(t => o[d].includes(t))));

Answer №2

const allData = {
  items: [{
      id: 1,
      categories: ['CategoryA', 'CategoryB', 'CategoryC']
    },
    {
      id: 2,
      categories: ['CategoryB', 'CategoryD']
    },
    {
      id: 3,
      categories: ['CategoryE', 'CategoryC']
    }
  ],
  filterQuery: {
    categories: ['CategoryA', 'CategoryB']
  }
};

console.log(allData.items.filter(item => allData.filterQuery.categories
  .some(query => item.categories.join(',').includes(query))));

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

Maintaining the Continuity of an Observable Stream Post Error Emission

Have you ever wondered how to handle errors from an observable without ending the stream? For instance, when making HTTP calls and encountering a 404 error or another type of error, throwing an error in the stream will cause it to stop and trigger the err ...

evaluate a utility function that operates on children

In managing a component that requires children (referred to as the layout component), there is a specific function nested within this component that processes these child components. Testing this function poses a challenge, so I decided to extract it into ...

Why is AJAX returning false and I'm unable to figure out the reason?

My goal is to perform a database query for a keyword instantly upon input change. Currently, I am able to successfully execute the query and store all the results. However, when attempting to display the results using GET, my ajax function returns false. W ...

Utilizing the same WebDriverJS instance repeatedly

As a beginner in Selenium, I successfully launched a website using the following Node.js code snippet: var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder() .forBrowser('chrome') .build(); console ...

Every time I attempt to execute route.js in my API folder, I encounter a persistent 404 error

Project Structure: https://i.stack.imgur.com/qMF6T.png While working on my project, I encountered an issue with a component that is supposed to call an API function. However, it seems like the file is not being found. I have double-checked the directory ...

Employing Ajax for interacting with a database

I am attempting to query my database using a JavaScript function for the first time, and I am struggling to get it to work. While unsure if this is the correct approach, it is the one that I have come across. Below is a simple snippet of my HTML code: < ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Error in Angular ngFor loop: Type 'OrderItem' is not compatible with type 'Iterable<any>'

In my HTML code, I have the following structure: <div class="grid mb-5" *ngFor="let orderItem of order.orderItems"> <div class="col-2">{{ orderItem.product.name }}</div> <div class="col-2&qu ...

In Angular 2+, what is the best method for displaying elements based on whether the user is logged in or logged out?

Struggling with the transition from AngularJS to Angular 2+ for my app. I'm facing challenges implementing a simple feature that was previously effortless in AngularJS. The issue is with the top navigation - I want it to display a LOG IN button when ...

Retrieve a collection containing all the variables that have been defined

I am attempting to gather all PHP defined variables and store them in an array. Previously, I tried: $myArr = get_defined_vars(); var_dump($myArr); The result was: array(4) { ["_GET"]=> array(0) { } ["_POST"]=> array(0) { } ["_COOKIE"]=> array ...

Updating the background of a button with Vue JS by utilizing an object upon clicking

If you have three buttons and want to change the background color when clicked, for example, clicking on the red button should turn the background color red. However, there is an important detail here: if you click on one button and then another, the old c ...

Effort to update Div element with Ajax fails to function

Looking for some assistance here. I'm attempting to update a database's entries using Ajax after submitting a form. The entries are displayed within a div. I've tried the following code to refresh only that specific div, but it doesn't ...

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

Display directional arrow on Ext.grid when the page is initially loaded

Displaying a grid with the product ID is our current setup. While the data is sorted according to the product ID, the sort arrow does not display upon page load. I have observed that clicking on the column reveals the arrow. How can we ensure that the so ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

What could be causing the EBUSY: resource busy or locked, open errno: -4082 error to appear while trying to build storybook 7 in next.js 13?

While attempting to create a storybook, I encountered the following error in my project: [Error: EBUSY: resource busy or locked, open 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modu ...

Is there a way to set up gulp without relying on npm when using shared hosting?

While working on my shared hosting, I encountered a roadblock regarding the installation of gulp for compiling LESS assets into CSS. The hosting administrator has declined to install npm, which is essential for setting up gulp. Given this limitation, I am ...

Substitute all web links contained within the DIV

Is there a way to change the URLs within a specific DIV? Here's an example of what I want to do: <div id="SearchList"> <a href="www.google.com/up">up</a> <a href="www.google.com/down">down</a> <a href="www.google.com/ ...

Default parameter in Node.js is set when the callback function is the last parameter

Here's a simplified version of the function I'm working with: doSmthg (name, age, callback) { callback(name, age); } I want to set a default value for age if it's not provided. In ES6, I could do doSmthg(name, callback, age=42) {...}, b ...

Issue with data not refreshing when using router push in NextJS version 13

I have implemented a delete user button on my user page (route: /users/[username]) which triggers the delete user API's route. After making this call, I use router.push('/users') to navigate back to the users list page. However, I notice tha ...