Filtering nested arrays within an array with a condition object in typescript

My object array (in Json format) looks like this:

var datas = [
  {
    "Id": "1",
    // Includes 10 fields
    "tests": [
            {
                "id":"1-1",
                "isSelected": true,
            },
            {
                "id":"1-2",
                "isSelected": false,
            },
        ]
  },
  {
    "Id": "2",
    // Includes 10 fields
    "tests": [
            {
                "id":"2-1",
                "isSelected": true,
            },
            {
                "id":"2-2",
                "isSelected": true,
            },
        ]
  },
  {
    "Id": "3",
    // Includes 10 fields
    "tests": [
            {
                "id":"3-1",
                "isSelected": false,
            },
            {
                "id":"3-2",
                "isSelected": false,
            },
        ]
  }
]

After trying the code below:

var filteredData = datas.filter( t => t.tests.filter(o => o.isSelected));

I need the data in the following format:

[
  {
    "Id": "1",
    // Includes 10 fields
    "t": [
            {
                "id":"1-1",
                "isSelected": true,
            }
        ]
  },
  {
    "Id": "2",
    // Includes 10 fields
    "tests": [
            {
                "id":"2-1",
                "isSelected": true,
            },
            {
                "id":"2-2",
                "isSelected": true,
            },
        ]
  }
]

Answer №1

You're making progress in the right direction, however, there is a slight error in your code. You are currently returning the inner filter result (an array) from your outer filter callback. Since an array is truthy, everything is being kept.

To correct this, you need to handle each outer object in two steps:

  1. Filter its tests, and

  2. Remove it completely if its tests is empty.

Here is the corrected code snippet:

var filteredData = datas.filter(t => {
  t.tests = t.tests.filter(o => o.isSelected);
  return t.tests.length !== 0;
});

var datas = [
  {
    "Id": "1",
    // Here 10 fields
    "tests": [
            {
                "id":"1-1",
                "isSelected": true,
            },
            {
                "id":"1-2",
                "isSelected": false,
            },
        ]
  },
  {
    "Id": "2",
    // Here 10 fields
    "tests": [
            {
                "id":"2-1",
                "isSelected": true,
            },
            {
                "id":"2-2",
                "isSelected": true,
            },
        ]
  },
  {
    "Id": "3",
    // Here 10 fields
    "tests": [
            {
                "id":"3-1",
                "isSelected": false,
            },
            {
                "id":"3-2",
                "isSelected": false,
            },
        ]
  }
]

var filteredData = datas.filter(t => {
  t.tests = t.tests.filter(o => o.isSelected);
  return t.tests.length !== 0;
});

console.log(filteredData);
.as-console-wrapper {
  max-height: 100% !important;
}

If you prefer a more concise arrow function, you can use the following:

Updated code snippet:

var filteredData = datas.filter(t =>
  (t.tests = t.tests.filter(o => o.isSelected)).length !== 0
);

var datas = [
  {
    "Id": "1",
    // Here 10 fields
    "tests": [
            {
                "id":"1-1",
                "isSelected": true,
            },
            {
                "id":"1-2",
                "isSelected": false,
            },
        ]
  },
  {
    "Id": "2",
    // Here 10 fields
    "tests": [
            {
                "id":"2-1",
                "isSelected": true,
            },
            {
                "id":"2-2",
                "isSelected": true,
            },
        ]
  },
  {
    "Id": "3",
    // Here 10 fields
    "tests": [
            {
                "id":"3-1",
                "isSelected": false,
            },
            {
                "id":"3-2",
                "isSelected": false,
            },
        ]
  }
]

var filteredData = datas.filter(t =>
  (t.tests = t.tests.filter(o => o.isSelected)).length !== 0
);

console.log(filteredData);
.as-console-wrapper {
  max-height: 100% !important;
}

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

The JavaScript code is not functioning properly on the server after the ajax request

I have a situation where an ajax request is sending data to a PHP file, and then the PHP file is generating HTML content with some JavaScript code. The JavaScript code includes Google's chart library, but unfortunately the chart is not working as inte ...

Incorporate live Twitch streaming onto a web platform

I'm currently in the process of making a website for a friends twitch stream and I'm very confused as to how I implement the twitch stream. I have created a div with the class "Twitchscreen" but I have no idea how I link to the twitch API or get ...

Can the grunt command be executed automatically after saving code in TypeScript?

As a newcomer to FrontEnd and JavaScript coding in TypeScript, I find myself constantly needing to follow these steps after making a code change: save the code -> compile it using Grunt -> reload the webpage. It can be quite time-consuming. Is there ...

Looking to add a dynamic divider between two columns that can be adjusted in width by moving the mouse left and right?

If you're looking for an example of two columns adjusting their width based on mouse movement, check out this page from W3Schools. I'm trying to implement this feature in my React app, but I'm unsure of how to proceed. Below is the JSX code ...

The WHATWG URL API allows creation of a new URL using the new URL

I've been experimenting with node and attempting to create an instance of the URL class to utilize its useful properties. Here's what I tried: const { URL } = require('url'); (...) http.createServer((request,response) => { let u ...

Prevent dragging functionality in ckeditor

Currently, I am encountering a problem with my ckeditor. The issue arises when I load a full page of HTML into the ckeditor. While it loads and displays correctly, I am seeking a way to restrict users from editing the alignment of the content, only allow ...

I must automate the process of navigating to a different page within my website

My current dilemma involves using the header() function in PHP to automatically redirect a user to another page on my site after they dismiss an alert() box. However, the desired outcome is not being met. Here are my requirements: 1) Display a JavaScript ...

Retrieve the value of a promise and transfer it to the subsequent function of an observable

For my Angular 9 application, I have created a custom interceptor called AuthorizationHeaderInterceptor: @Injectable() export class AuthorizationHeaderInterceptor implements HttpInterceptor { constructor(private authenticationService: AuthenticationSer ...

Add the teams-js library to your Vue.js project

I'm currently working on integrating the Microsoft Teams SDK into my Vue.js project. After installing the npm package and referencing it in my vue-file, I noticed that the microsoftTeams alias is displaying as undefined. Is there a step I may have ove ...

The JavaScript counterpart to jQuery's click event handler

I'm trying to figure out how to achieve the same effect as this jQuery code. var divQuery = $('.html5gallery-thumbs-0').children(); divQuery.on('click', function () {...} I attempted it like this: var divQuery = document.g ...

Issue with updating dropdown values in real-time in React

I am a beginner with React and I have a question regarding fetching dropdown values from the backend. Despite using async-await functions, the list is not getting populated with items. Any assistance in this matter would be greatly appreciated. Here is th ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

Troubleshooting problems in transferring JSON data between a React application and a Spring Boot service running locally

Running a local Springboot server, accessing it locally in the browser returns a properly formatted JSON object. However, encountering issues when trying to fetch this JSON object from a React application running on node locally. Managed to overcome CORs h ...

Error message: "Receiving a 'TypeError' in Node.js async parallel - the task is not recognized as a

Currently, I am utilizing the async module to run multiple tasks simultaneously. In essence, I have two distinct files named dashboard.js and Run.js. Dashboard.js module.exports = { func1 : function(){ console.log(“Function one”); }, ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...

Iterating through every image displayed on a webpage

Two inquiries: What is the best way to efficiently loop through every image on a specific webpage and open each one in a new browser tab? Similar concept, but instead of opening in a new tab, I am interested in substituting different images for the ...

Error encountered with TypeScript compiler when using a React Stateless Function component

I am attempting to create a React Stateless Function component using TypeScript. Take a look at the code snippet below: import * as React from 'react'; import {observer} from 'mobx-react'; export interface LinkProps { view: any; ...

Struggling to figure out how to make Bootstrap toast close or autohide properly

Looking to integrate Bootstrap 5 toasts into my ASP.NET web application, I have the code below. HTML <div class="row"> <div class="toast" id="companyUpdOK" name="compa ...

Using the ng-repeat directive in an angular-nvd3 tooltip

Looking to dynamically repeat values in the tooltip content of an nvd3 graph? Not sure how to achieve this using ng-repeat with JSON data? Seeking guidance on alternative methods? I can help! $scope.options = { chart: { type: ...