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

When attempting to asynchronously observe a datasource, the 'number' type cannot be assigned to the 'NgIterable<any>' type

I'm currently working with this simplistic component: import { Component, VERSION } from '@angular/core'; import { Observable, Observer } from 'rxjs'; @Component({ selector: 'my-app', templateUrl: './app.compone ...

Having trouble getting the Next.js Image component to work with Tailwind CSS

Recently, I've been working on transitioning a React project to Next.js and encountered some issues with the next/Image component that seem to be causing some problems. <div className=" flex flex-col items-center p-5 sm:justify-center sm:pt-9 ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

I'm attempting to navigate my way through working with a PHP array, but I seem to be struggling

Here is a snippet from my CSV file: #file contents EC023,2 EC026A,3 EC025,7 EC027,67 EC031,567 EC033,78 EC034,234 EC038,67 EC038A,67 EC039,60 EC039A,100 Using the PHP library ParseCSV, I successfully loaded the file data into an array. Array ( [0] => ...

Displaying JSON data using Vue.js

fetching JSON data save movieData: {} ...... retrieveMovieData (context, parameter) { axios.get(API.movieData + parameter.id) .then(response => { context.commit('MOVIE_DATA', response.data) }) .catch(error => ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

Not enough resources error in ajax code for live update clock functionality

Recently, I developed a real-time clock that updates every second. Surprisingly, when I tested it on my local environment, everything worked perfectly without any errors. However, the situation drastically changed when I decided to upload it to my web host ...

Using the `setTimeout` function to swap components

As I work on implementing a setTimeout method, the goal is to trigger an event after a .5 second delay when one of the three buttons (drip, french press, Aeropress) is pressed. This event will replace {{ShowText}} with {{ShowText2}}, which will display &ap ...

Align the text on the same horizontal line

I have been struggling with this issue for hours. Here is my Header.js <div className="navbar-inner"> <h2>Text1</h2> <h3>Text2</h3> </div> This is the content of my Header.css: .navbar-inner { ...

Tips for positioning the overlay to match the icon list when hovering- JavaScript/Cascading Style Sheets (CSS)

My challenge involves a list of <li>'s accompanied by an icon that, when hovered over, displays an overlay containing information about the 'test'. The setup looks something like this: test1 test2 test3 and so forth.... Here' ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

Building an integrated Monaco editor using Electron and AngularJS

Struggling to integrate the Monaco editor into my Electron app. Despite following electron examples, encountering persistent errors in my application. The errors I'm facing include: "loader.js:1817 Uncaught Error: Unrecognized require call" "angula ...

What steps are necessary to integrate expo-auth-session with Firebase?

I am working on implementing a feature in my code that will allow users to login and authenticate using their Google credentials. Once they successfully log in, I want them to be added to my authentication database in Firebase. My attempt to achieve this ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

What makes Twitter Bootstrap special that modal events function in JQuery but not in pure JavaScript?

When working with the Twitter Bootstrap modal dialog, there is a set of events that can be utilized with callbacks. For instance, in jQuery: $(modalID).on('hidden.bs.modal', function (e) { console.log("hidden.bs.modal"); }); I ...

Angular Path Navigation Issue

Below is the route configuration that I am currently using: { path: '', component: FrontEndMainComponent, children: [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { pa ...

Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code: public fetchResults(searchTerm: string): Observable<Array<SearchResult>> { let params = new HttpParams().set('searchTerm', searchTerm); return this.http .get<Array< ...

Error message displayed by console when attempting to parse JSON data that is in array

After receiving a simple array as my JSON response: [35,55] The Chrome network inspector confirms that it is valid JSON. However, when attempting to parse the xhr.responseText using JSON.parse, I am confronted with the error: Uncaught SyntaxError: Unexpe ...