I'm looking to filter this array based on the value of a subarray that the user will specify the key and value for. How can I accomplish

Given the input var key="value_0" and var input="hello", I need to filter the array in TypeScript based on these values. The filtering criteria involve checking if the array elements contain a subarray with key="value_0" and if the value of this key includes the input provided using the .includes method.

public list: any = [{
    "header": "API",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghn",
        "value_4": "l"
      },
      {
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  },
  {
    "header": "CLOUD",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      },
      {
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  },
  {
    "header": "OTHER HEADER",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      },
      {
        "value_0": "yello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  },
  {
    "header": "YET ANOTHER HEADER",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      },
      {
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  }
];

If the user provides key="value_o" and input="hel", we need to filter the list by searching for the key within the data subarrays and then checking if the value includes the input provided. The final result will be an array of elements where both the key and the value match the user input. For example, filtering with key='value_0' and input='hell' will yield the same result as each index in the data attribute contains a subarray with the attribute value_0 and its value includes the input text.

[
  {
    "header": "API",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghn",
        "value_4": "l"
      },
      {
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  },
  {
    "header": "CLOUD",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      },
      {
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  },
  {
    "header": "OTHER HEADER",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      },
      {
        "value_0": "yello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  },
  {
    "header": "YET ANOTHER HEADER",
    "data": [{
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      },
      {
        "value_0": "hello",
        "value_1": "abc",
        "value_2": "def",
        "value_3": "ghi",
        "value_4": "jkl"
      }
    ]
  }
];

Answer №1

1)

any.map(el=>({header:el.header,data: el.data.filter(data=>data[key] && data[key].includes(input))})).filter(el=>el.data.length);

Outputs:

...
data: [ 
 {
 value_0: "hello",
 value_1: "abc",
 value_2: "def",
 value_3: "ghi",
 value_4: "jkl"
 }
 //second obj removed, as it contains yello != hel 
 ],
 header: "OTHER HEADER"
  ...

http://jsbin.com/higopoloka/edit?console,js

2)If you simply wish to display only 'value_0' instead of the entire surrounding array, you can use:

any.map(el=>({header:el.header,data: el.data.reduce((arr,obj)=>obj[key]&&obj[key].includes(input)?!arr.push([obj[key]])||arr:arr,[])})).filter(el=>el.data.length);

Output:

[{
   data: [],//ive removed the value_0 here to show what happens
   header: "API"
  },
  {
    data: [["hello"], ["hello"]],
    header: "CLOUD"
  },
  {
   data: [["hello"]],//only one, as yello !== hel
   header: "OTHER HEADER"
  },
  {
   data: [["hello"], ["hello"]],
   header: "YET ANOTHER HEADER"
 }]

1/2) If you also want the main elements to be hidden if their data is empty, do this (which is already part of the above codes):

.filter(el=>el.data.length); 

http://jsbin.com/qabenedite/edit?js,console

Answer №2

One way to search for a specific value in an array in JavaScript is to use a loop. The snippet below demonstrates this approach:

var list = [{"header":"API","data":[{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghn","value_4":"l"},{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"}]},{"header":"CLOUD","data":[{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"},{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"}]},{"header":"OTHER HEADER","data":[{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"},{"value_0":"yello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"}]},{"header":"YET ANOTHER HEADER","data":[{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"},{"value_0":"hello","value_1":"abc","value_2":"def","value_3":"ghi","value_4":"jkl"}]}];


var key = 'value_0';
var val = 'hello';
var search = '';

for(var i in list)
{
for(var j in list[i]['data'])
  {
  if(typeof(list[i]['data'][j][key]) !== 'undefined' && list[i]['data'][j][key] === val)
    {
    search = list[i]['data'][j];
    break; 
    }
  }
}
console.log(search)

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

shortcut taken in inferring now exported

When using a default export, if the expression consists only of a variable identifier, the type inferencer defaults to the declaration of the variable instead of the actual type of the expression. Is this behavior intentional or is it a bug? // b.ts const ...

Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions: export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } ...

Is it possible to use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

Divergence between two distinctive occurrences in Google Analytics

Why are there differences in the number of unique events recorded by Google Analytics for two consecutive events? I have set up onClick tracking for a button. When the button is clicked, an event (Event 1) is sent to Google Analytics and a CSS-selector ap ...

What are the steps to include a string into Vue and then assess its value?

Where should I define a function in a SPA using the options API that will be called from an HTML href? Check out this demo on Codepen where everything works fine: CODEPEN However, when I try to implement it in my single-page application: <templat ...

Unit Testing Angular: Mastering Unit Testing for the .map() Function

I am in need of testing a service method, but I am unsure about how to achieve complete coverage for the code that gets executed as a result of calling another injected service method. The Service Method to be tested: @Injectable() export class BomRevisi ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

AngularJS 1 - CSS glitch occurs when navigating between tabs

Upon loading my homepage, it appears as follows: https://i.sstatic.net/CTlj1.png Initially, certain rows were filled with a blue background color using ng-class, specifically "row-answered-call" as shown below: <tr ng-repeat="item in list" ng-class=" ...

Is there a way to successfully parse this JSON without encountering any exceptions?

Below is the JSON data that I am working with: [ { "outcome": "Success", "message": "", "identity": "", "delay": "0", "symbol": "AAPL", "companyname": "Apple Inc.", "date": "Jun 08", "time": " 4:52 PM EDT", "open" ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

What is the correct way to use getServerSideProps?

Lately, I've been exploring the world of web development by creating a web app using NextJS. While I have some knowledge of the basics in this field, I found myself a bit lost when working with NextJS since I hadn't worked with React before. One ...

Tips for successfully passing a component within a React Material-UI MenuItem

I included the Report.js component and successfully used it within a "button" element import Reports from 'new-components/Reports/Reports' //ontop <Button> <Reports pid={pid} /> //working </Button> However, ...

Updating the component following an API request in ReactJS

I'm currently working on a component that allows users to search for friends by entering their email address. The interface consists of an input form where users can submit the email and I want to display the friend's information below the form a ...

What is the best method for retrieving the correct city name using latitude and longitude with the Google API?

Using the following query http://maps.googleapis.com/maps/api/geocode/json?latlng=35.6723855,139.75891482, I am able to retrieve a list of various locations based on the provided coordinates. However, I am specifically interested in obtaining only the ci ...

Incorporate an icon into an Angular Material input field

I want to enhance my input search bar by adding a search icon from Angular Material : <aside class="main-sidebar"> <section class="sidebar control-sidebar-dark" id="leftMenu"> <div> <md-tabs md-center-tabs id=" ...

Removing a directory from GitHub with the help of octokit/rest

I am attempting to utilize octokit/rest in order to programmatically remove a directory. Below is the code I am using: import {Octokit as Github} from '@octokit/rest'; const githubToken = "read from vault"; // Functions for retrieving current c ...

Identify whether the application is built with nextJS, react, or react-native

I'm currently developing a library for React applications and I anticipate that certain features will function differently depending on the environment. I am seeking a method to identify whether the current environment is a ReactJS application (creat ...

What is the best way to display JSON within a partial?

Within my Rails app, I have implemented a JavaScript graph. Whenever I click on a circle in the graph, it displays the name of the corresponding user. Now, my goal is to retrieve additional information from the related database table based on this user&apo ...

Guide to creating an Express + TypeScript API using an OpenAPI 3.0 specification

After creating specifications for my REST API server using OpenAPI 3.0, I found myself wanting to generate an expressjs app quickly instead of manually writing repetitive code. However, the generated code from editor.swagger.io is in javascript, which does ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...