Filter the array while maintaining its current structure

I'm struggling to create an array filter that can handle exact and partial data within a nested array structure. The challenge is maintaining the integrity of the top-level structure while filtering based on data in the second layer. Here's an example json:

{
  OpenClientIndicator: false,
  listTypeCreditOffer: [{
         companyName: 'itau',
         offerCard: [{
                 nameCard: 'black',
                 idCard: 10,
                 availableValue: 10000.00
         },{
                 nameCard: 'platinum',
                 idCard: 9,
                 availableValue: 5000.00
         },....]
         id:1
       },{
         companyName: 'santander',
         offerCard: [{
                 nameCard: 'black',
                 idCard: 100,
                 valor: 15000.00
         },{
                 nameCard: 'platinum',
                 idCard: 90,
                 availableValue: 7000.00
         },....]
         id:2
       },...]
}

The filter criteria are based on nameCard and id Card, while preserving the original structure. For instance, if the filter value is 10, the expected output should be as follows:

{
  OpenClientIndicator: false,
  listTypeCreditOffer: [{
         companyName: 'itau',
         offerCard: [{
                 nameCard: 'black',
                 idCard: 10,
                 availableValue: 10000.00
         }
         id:1
       ]
}

However, I'm encountering a problem where the current structure only processes the first record it matches and doesn't scan through all arrays in the first layer.


let cards;
const newDados = jsonArray.listTypeCreditOffer.forEach((offer) => {
  cards = offer.offerCard.filter((card) => { 
       if( card.idCard.toString().includes(filterValue.toUpperCase()) ||
           card.nameCard.toUpperCase().includes(filterValue.toUpperCase())) {
           return card;
       }
  });
 });

This is where I need to refine my logic to address this issue.

Answer №1

It is important to handle things with caution by using the spread operator ... to create a duplicate of the element's properties, then defining the filtered property.

dataModified = {
    ...this.data,   //all properties of this.data
                    //except for listTypeCreditOffer

    listTypeCreditOffer: this.data.listTypeCreditOffer
      .map((x: any) => ({
        ...x,       //all properties of this.data.listTypeCreditOffer
                    //except for offerCard which will be modified
                    //In this case, a specific condition is "hardCoded"
                    //Normally, you would use more complex expressions
                    //such as your example
                    //card.idCard.toString().includes(filterValue.toUpperCase()) ||
                    //card.nameCard.toUpperCase().includes(filterValue.toUpperCase()))
                    
        offerCard: x.offerCard.filter((card: any) => card.idCard == 10),
      }))
      .filter((x) => x.offerCard.length > 0), //only retrieve the 
                                              //offerCard array if it's not empty
  };

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

ESLint is reminding you that the `parserOptions.project` setting must be configured to reference the tsconfig.json files specific to your

Within my NX Workspace, I am developing a NestJS-Angular project. Upon running nx lint, an error is triggered with the following message: Error: A lint rule requiring the TypeScript type-checker to be fully available has been attempted, but `parserOptions. ...

Creating dropdown options within a DataGrid in Form.IO: A step-by-step guide

I'm currently working with the Form.IO JS library to develop a new form. Within this form, I need to include a DataGrid containing 11 components. To ensure all components fit inline, I have applied the CSS rule overflow: auto (overflow-x: auto; overfl ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

The file functions/lib/functions/src/index.ts is missing, preventing the deployment of Cloud Functions

Whenever I attempt to deploy my Firebase cloud functions, I encounter the following error. Expected outcome: Successful deployment of functions. Error: Error: An issue occurred while reading functions/package.json: functions/lib/index.js is missing and ...

The post body is incomplete and is lacking the necessary parameter "To" that

It seems there might be a configuration issue either in the header or the body. Should I make changes to the headers or is it possible that the body is misconfigured? const axios = require('axios'); const url = '/my_url'; const aut ...

A regular expression in Javascript that can be used to identify at least one word starting with a number among multiple words, with a

Currently, I am utilizing JavaScript Regex to validate an input field based on specific conditions: The value must consist of only alphabets and numbers There should be a minimum of two words (more than two are allowed) Only one word can start with a num ...

Dependency on Angular's HTTP service inside a component

I've been experimenting with loading data from a static JSON file as part of my journey to learn angular templating. After some searching online, I came across a few examples. However, I want to steer clear of implementing a service until I have a be ...

Typescript: Creating an interface for a nested object "with a required key"

The objective is to prevent developers from declaring or accessing fields that the object does not possess. This also involves accurately defining a deeply nested object or schema. const theme: iTheme = { palletes: { primary: { main: "white", ...

Using jQuery's .load function to load an HTML file from a href attribute into a div element may not function as

I'm struggling to populate the href section of my dropdown menu with my files. I'm attempting to dynamically load the files in the .where-you-tune class. Something must be off because I keep encountering (index):81 Uncaught TypeError: $(...). ...

The __call__ function in Python classes does not support vectorization

I am attempting to graph a function by utilizing the __call__ method within a custom class. import math import numpy as np import matplotlib.pyplot as plt class F: def __init__(self, n, m): self._n = n self._m = m def __call__(sel ...

Google Maps in Angular is not showing up

My Angular Google Maps implementation seems to be working, but unfortunately, the map is not showing on my website. I have confirmed that my JS is loading the maps and I can retrieve the map properties. Interestingly, when I check the Chrome AngularJS Debu ...

The system cannot locate the module: Unable to find '@reactchartjs/react-chart-2.js'

I've been working on implementing this chart using the npm module called react-chartjs-2. I followed these steps to install the module: Ran the command: npm install --save react-chartjs-2 chart.js As a result, my package.json file now looks like th ...

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

Harnessing the power of Material-UI's muiThemeable with Typescript

I'm trying to access the current theme colors within a custom React component. The example I'm referencing is from Material UI http://www.material-ui.com/#/customization/themes Despite attempting various approaches, I'm unable to get Typesc ...

What sets apart an Angular component from a module?

After watching numerous videos and reading various articles, I came across this particular article that left me feeling confused. In the beginning of the article, it mentions: In Angular, applications are structured in a modular way. Each Angular app consi ...

Utilizing ng-class with Boolean values in AngularJS

On my page, I have a pair of buttons that control the visibility of elements using ng-hide and ng-show. <a ng-click="showimage=true" ng-class="{ 'activated': showimage}" class="button">Images</a> <a ng-click="showimage=false" ng-c ...

What is the reason behind line-height not affecting the clickable area when reduced?

I have been working on a personal project where I added thumbnails for images that can be scrolled through and clicked to set the main image. However, I encountered a strange issue. To demonstrate the problem, I created a Stackblitz project here: https:// ...

Tips on choosing just the selected checkbox values

In my CodeIgniter view, I am utilizing AJAX to post data to my controller. <script type="text/javascript"> $(document).ready(function(){ // find the input fields and apply the time select to them. $('#sample1 inp ...