How can you loop through an array of objects in TypeScript without relying on the traditional forEach

Currently, I'm working on an array of objects with the following structure.

[
    {
        "matListParent": "CH",
        "dParent": "CUST1",
        "isAllSelected": true,
        "childItems": [
            {
                "item": "Display1",
                "isSelected": true
            },
            {
                "item": "Display2",
                "isSelected": false
            }
        ]
    },
  {
        "matListParent": "CH2",
        "dimParent": "CUST2",
        "isAllSelected": true,
        "childItems": [
            {
                "item": "Display5",
                "isSelected": true
            },
            {
                "item": "Display6",
                "isSelected": false
            }
        ]
    }
]

I am attempting to retrieve the value of the item where isSelected is true. My attempt so far has been as follows:

data.filter(
        (matModel: any) => matModel.matListParent === "CH").map(
          (model: any) => model.childItems).map((item: any) => item).filter((list: any) => list.isSelected);

However, this code returns an empty array. What error may have occurred in my approach? Your help is greatly appreciated.

Thank you for your assistance.

Answer №1

Solution code

data.filter(
        (matModel: any) => matModel.matListParent === "CH").map(
          (model: any) => model.childItems).map((item: any) => item[0]).filter((list: any) => list.isSelected);

Explanation of the problem

Upon executing the first

filter((matModel: any) => matModel.matListParent === "CH")
and the first
map((model: any) => model.childItems)
, we end up with an array of arrays as shown below

[
  [
    { item: 'Display1', isSelected: true },
    { item: 'Display2', isSelected: false }
  ]
]

When attempting to apply another map((item: any) => item) on this resultant array, it produces the same output. Consequently, the final

filter((list: any) => list.isSelected)
will not return anything.

The provided solution is intended to guide you in addressing this issue, but there are multiple ways to tackle it. We trust that you now have a clearer understanding of where things may be going wrong.

Answer №2

give this a try

const data = array
.filter((elem) => elem.matListParent === "CH")
.map(elem => elem.childItems.filter((val) => val.isSelected));

result: you will only receive =

const array = [
  {
    matListParent: "CH",
    dParent: "CUST1",
    isAllSelected: true,
    childItems: [
      {
        item: "Display1",
        isSelected: true
      },
      {
        item: "Display2",
        isSelected: false
      }
    ]
  },
  {
    matListParent: "CH2",
    dimParent: "CUST2",
    isAllSelected: true,
    childItems: [
      {
        item: "Display5",
        isSelected: true
      },
      {
        item: "Display6",
        isSelected: false
      }
    ]
  }
];

const data = array
  .filter((elem) => elem.matListParent === "CH")
  .map(elem => elem.childItems.filter((val) => val.isSelected)).flat(Infinity);
  
  console.log(data)

[
  { item: 'Display1', isSelected: 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

Angular Input Validation for Multiple Entries

Has anyone else tried creating a validator that checks for duplicate email addresses in a list? I am attempting to implement this feature where the validator takes an email address from a text input and compares it against a list of emails. The code snipp ...

Encountering build issues with Next.js on Vercel and local environments

As I work on my first Next.js website, I encountered a build error that persists both locally and on Vercel. Interestingly, I managed to achieve a successful local build at one point, but it no longer works. Here is an excerpt from my package.json: ...

Error message in VsCode plugin stating that property 'X' is not found on type '{}' within a Vue 3 template

Currently, I am in the process of setting up my vue-cli project that utilizes the composition API with <script setup> to fully integrate TypeScript. Each time I try to use variables within template tags, VSCode flags errors. I have already installed ...

How can you create a type in Typescript that is composed of a specific property taken from another type?

I'm still in the process of understanding typed languages, but imagine I have the following scenario: export interface Person { id: number; name: string; } const persons: Array<Person> = [ { id: 1, name: 'foo', }, { ...

Uploading videos on Mobile Safari causes the website to refresh automatically

Setting up a photo uploading server on a raspberry pi using Angular with Node.Js and multer has been an exciting project for me. I opted to host it on an unsecured ad-hoc network created by the pi itself so I can easily take it on road trips and store phot ...

Oops! The react-social-media-embed encountered a TypeError because it tried to extend a value that is either undefined, not a

I recently attempted to incorporate the "react-social-media-embed" package into my Next.js project using TypeScript. Here's what I did: npm i react-social-media-embed Here is a snippet from my page.tsx: import { InstagramEmbed } from 'react-soc ...

Information sent from TypeScript frontend to Java backend is converted into a LinkedHashMap

I have a situation where my typescript frontend is communicating with my java backend using REST. Recently, I added a new simple rest endpoint but encountered an issue when trying to cast the sent object properly because the body being sent is a LinkedHash ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

Exploring the capabilities of Vue combined with Typescript and Audio Worklets

I've encountered a challenge with configuring Vue to compile audio worklets. Specifically, I am facing a similar issue to this problem that has already been resolved, but using Typescript instead of JavaScript. My approach was to include the ts-loader ...

Checking the value of a row in an Angular Material table when a checkbox is

I am working with an Angular Material table that has rows with checkboxes. To view the example of this, please visit Material Table. I would like to perform a manipulation on other fields based on the checkbox selection status of a row. ...

How to temporarily modify/add CSS class in Angular 2

In my Angular 2 application, there is a label that displays the current amount of points for the user. Whenever the number of points changes, I want to briefly change the class of the label to create an animation effect that notifies the user of the chang ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Is it possible to customize a row with checkboxes in ng2-smart-table when creating a new row?

When adding a new row, I would like a checkbox in the Status column and an input text field in the Image column. You can see an example image here. ...

Avoid Inferring as a Union Type

I am currently working on implementing a compact type-safe coordinate management system in TypeScript. It revolves around defining the origin of the coordinate as a type parameter, with functions that only accept one specific origin type. Below is a short ...

What could be the reason behind my Heroku app suddenly crashing without any visible errors?

After successfully starting the Nest application, about 50 seconds later it transitions from 'starting' to 'crashed'. The last log entry before the crash is a console log indicating the port number. View Heroku logs after successful bui ...

The element type 'ReactElement<any>' does not match a JSX element constructor function. 'undefined' cannot be assigned to type 'Element | null'

After attempting the suggested fix of deleting node_modules/ and yarn.lock, then reinstalling everything, I still cannot resolve the issue. I am currently developing a basic router that renders children based on a certain prop: import React, { Fragment } ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

I'm curious about how to implement textarea functionality within Angular for modeling purposes

I have a desire to utilize the model and transmit it to the server. One instance of this is sending comments. comment.model.ts export interface Comment { article_no: number; username: string; nickname: string; creatat: Date; content: string; } ...

Potential Null Object in Typescript Mongoose: A Concern

Encountering an issue while attempting to locate my user model: Object is possibly 'null'. I would like to find a solution that does not involve suppressing TypeScript's strict rule. const { email, password } = req.body; const user = awai ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...