Angular 2: Refine array based on a condition

I need to filter data in an object array based on a predicate. The tricky part is constructing the predicate, which should be similar to building a query using a Map data structure.

Here is an example of my objects array:

var data = [
   {"id": 1, "name": "bob", "address": "123 abc", "status": "active"},
   {"id": 2, "name": "henry", "address": "123 def", "status": "inactive"},
   {"id": 3, "name": "henry", "address": "123 hij", "status": "active"}
];

And here is the Map structure that should be used to construct the predicate:

var map = new Map<string, any>();
map.set("name", ["henry", "bob"]);
map.set("status", "active");

The desired output for this scenario would be:

[{"id" : 3, "name": "henry", "address": "123 hij", "status": "active"}]

Now, I'm struggling with how to write the data.filter((item) => {...}) function dynamically to build the predicate and filter the results without hardcoding property names. Additionally, the value could be a string, array, or a number. The hypothetical predicate should look like this:

data.filter((item) => 
{ item["name"] IS IN map.get("name").values[]
  && item["status"] IS EQUAL TO map.get("status").value)});

I'm finding it difficult to convert the Map object into a usable predicate for filtering. Any tips or guidance on this matter would be greatly appreciated.

Answer №1

Here's a quick and simple solution to guide you in the right direction, tailored for your basic dataset:

const checkCriteria = item => {
  for (let [key, value] of map) {
    if (!item.hasOwnProperty(key)) return false;
    if (typeof value === 'number') {
        if (item[key] !== value) return false;
    }
    if (!value.includes(item[key])) return false;
  }
  return true;
};

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

Transform the elements of a tensor in TensorFlow into a standard JavaScript array

Having utilized the outerProduct feature within the TensorFlow.js framework on two 1D arrays (a,b), I am faced with a challenge in obtaining the values of the produced tensor in regular JavaScript format. Despite attempts using .dataSync and Array.from(), ...

The hide-columns feature in Ng-table does not allow for manual column hiding from the controller

I've configured ng-table with checkboxes to toggle column visibility, and it's functioning smoothly. Here's the HTML: // Switchers to show/hide columns <div style="margin-bottom: 20px"> <label class="checkbox-inline" ng-repeat= ...

Exploring Vue.js: Leveraging External JavaScript/JQuery Functions

I am currently working on developing a lightbox/modal feature using Vue.js. After making significant progress, I have encountered the need to utilize existing functions from another Javascript/Jquery file. Due to the complexity of these functions, rewritin ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

Guide on decrypting AES 128 in CryptoJS for both nodejs and web browsers

Utilizing a node.js server, I have successfully encrypted and decrypted a JSON in Base64 with the crypto node module using IV & Key. However, when I send an emit action with my AES 128 CTR JSON to a web client, I receive the JSON with base64 data encr ...

Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click. pauseTask: function() { this.isOpen = !this.isOpen; this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume'; }, While it works flawle ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

Utilizing a C array to store a collection of structures, followed by attempting to access the array using a pointer directed at the initial

Currently, I am utilizing an array to store structures (the structure being Path) which is defined in the following manner: Path **array = malloc(items * sizeof(Path *)); Subsequently, each element is allocated as follows: for (i=0;i<items;i++) { ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...

Strengthening the vulnerability of open redirects in JavaScript

let input=document.getElementById("example").value; let newUrl= "http://localhost/app/default.aspx?example="+input; Window.showModalDialog(newUrl); I've noticed that the showModalDialog method may result in a potential open redirect vulnerability. Is ...

Prevent the execution of an event while another event is already running in jQuery

Two events are in play here: one with the onclick function which scrolls to a specific div upon menu item click, and the other utilizes the onscroll function to "highlight" the corresponding menu item when scrolling near the div. The burning question is: ...

Having trouble with jQuery's getJSON function throwing an error?

I have been working on a project where I am using the getJSON function to fetch JSON data from an API that I am developing. However, I am facing an issue where the getJSON function always triggers the error handler. Below is the JavaScript code I am using: ...

The system encountered an error while trying to access the property "slug

I am currently working on a project that involves using next.js and wordpress. I have set up my api.js file, but I encountered an issue when trying to access the [slug] property from another component. The error message displayed is "Typerror: Cannot read ...

Retrieving data from a promise in Redux

Is there a way to access the data of the first dataElement in the array and log its name using console.log? import React, { Component } from 'react'; class Submit extends Component { componentDidMount() { const programStage = this.p ...

The Javascript eval method throws a ReferenceError when the variable is not defined

In my constructor, I was trying to create a dynamic variable from a string. Everything was working smoothly until I suddenly encountered this error out of nowhere. I didn't make any changes that could potentially disrupt the system, and the variables ...

Declaring data types in a NextJS project

Exploring the realms of NextJS and TypeScript, I find myself embarking on a project for practice. A thought crosses my mind - would it be wise to consolidate all my type definitions into a single file like global.d.ts? Could this possibly impact the perfor ...

Show various forms that gather information

Upon selecting an option from the drop-down menu, a certain number of forms will be displayed with captured data. For example: Imagine owning a form with fields such as No. of Applicants, Applicant Name, Telephone, E-mail, etc... If the user selects 2 fo ...

Sending two objects back in res.send() in an API: A step-by-step guide

I've got an API that looks like this router.get('/exist', async (req, res) => { try { const { user: { _id: userId } } = req; const user = await User.findById(userId); const profile = await Profile.findById(user.profile, &apo ...

Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements: const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, ...