Discover how to validate a property within an array of objects and add the accurate values to a fresh array using TypeScript

I have a list of objects and I want to create a new array that contains only the objects with the 'read' property set to true. I've tried a couple of different methods, but I keep getting an error: Uncaught TypeError: Cannot read properties of undefined (reading 'push').

Here is my first method:

docList.forEach(item => {
        if(item.read === true) {
            readArray.push(item);
        };
    });

And here is my second method:

for (var i = 0; i < docList.length; i++) {
        if (docList[i].read) {
            readArray.push(docList[i]);
        }
    }

This is the complete file:

import './Main.css';
import { useState } from 'react';

type DocumentType = {
    id: number;
    title: string;
    read: boolean;
};

export default function Main() {
    const [docList, setDocList] = useState<DocumentType[]>([
        { title: 'doc 1', id: 1, read: true },
        { title: 'doc 2', id: 2, read: false },
        { title: 'doc 3', id: 3, read: true },
        { title: 'doc 4', id: 4, read: false },
        { title: 'doc 5', id: 5, read: false }
    ]);
    let readArray: DocumentType[] = [];

    docList.forEach(item => {
        if (item.read === true) {
            readArray.push(item);
        };
    });

    /* for (var i = 0; i < docList.length; i++) {
        if (docList[i].read) {
            readArray.push(docList[i]);
        }
    } */

    return (
        <div>
            main
        </div>
    );
};

Answer №1

The issue you are encountering stems from not initializing the readArray variable before attempting to push elements into it. To resolve this, simply initialize readArray as an empty array prior to the loop.

let readArray: DocType[] = [];

I have made the necessary adjustment to your code.

import './Main.css';
import { useState } from 'react';

type DocType = {
    id: number;
    title: string;
    read: boolean;
};

export default function Main() {
    const [docList, setDocList] = useState<DocType[]>([
        { title: 'doc 1', id: 1, read: true },
        { title: 'doc 2', id: 2, read: false },
        { title: 'doc 3', id: 3, read: true },
        { title: 'doc 4', id: 4, read: false },
        { title: 'doc 5', id: 5, read: false }
    ]);
    let readArray: DocType[] = [];

    docList.forEach(i => {
        if (i.read === true) {
            readArray.push(i);
        }
    });

    return (
        <div>
            main
        </div>
    );
};

Answer №2

Try filtering instead of pushing, and don't forget to utilize the useMemo hook for the readArray:

const readArray = useMemo(() => {
  return docList.filter(doc => doc.read)
}, [docList])

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

A powerful trio: Axios, Typescript, and Promises

I am facing a TypeScript dilemma. I have a REST method that is being called within my http library by Vue action. I want the resolve() method to return the typed array, but if I do not convert it within the action.ts "then" method, I get a '.length do ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

React Alert: It is important for every child within a list to have a distinct "key" prop, not due to a missing key in the map

My current project involves developing a React 18 application. While working on one of the pages, I encountered the following error: https://i.sstatic.net/9Mk2r.png I am aware that this type of error is often linked to the absence of a unique key in the m ...

An observable value is intertwined with another observable

indexData and indexEditData serve as the observables within my application. The purpose of indexData is to store a json object that is used to populate a table. Editing of table rows is facilitated by selecting individual rows, triggering the transfer of t ...

What is the purpose of the tabindex in the MUI Modal component?

Struggling with integrating a modal into my project - it's refusing to close and taking up the entire screen height. On inspection, I found this troublesome code: [tabindex]: outline: none; height: 100% How can I remove height: 100% from the ...

Creating an Array in Angular 4

My goal is to populate an array with dynamic data. export class Test implements OnInit { private lineChart: Array<any>; } As I work on the code, I am dynamically generating some data and pushing it into the empty lineChart array. While this proc ...

Declaration of Typescript index.d.ts for a heavily nested function within an npm module

Regrettably, it appears that @types/rickshaw is lacking content, prompting me to create my own declaration file. The current one I have looks like this: declare module 'rickshaw' { export class Graph { constructor(obj: any); ...

What is the best way to ensure that GCM push notifications are still received even when the app is closed or the

Currently, I'm in the process of developing an application using Ionic 2 that requires push notifications to be received. In certain scenarios, such as when the app is force-stopped on Android or when the device is turned off, push notifications are ...

Xtermjs does not support copying and pasting functionalities

I'm struggling to enable the copy & paste feature in my terminal using xterm.js APIs. My goal is to allow users to copy strings from the clipboard. Currently, I have implemented the following code: this.term.onKey((key) => { if (key.domEven ...

Bypassing disputes in a TypeScript function

I attempted to implement the solution provided by Pacerier in response to the question about skipping arguments in a JavaScript function. However, it doesn't seem to be working for me. The function I am dealing with has numerous arguments. this.servi ...

When working with TypeScript for initial data, you have the choice between using interface types or class types. Which approach is the

When working with initial data in TypeScript, you have the option to use either an interface type or a class type. Which approach is preferable? export interface Item{ text: string, value: number } itemModel: ItemComboBox = { value:'valu ...

Is there a way to enhance a generic parameter using another generic parameter in TypeScript?

I am struggling with repetitive code that involves a type with minor variations: import { ComponentPropsWithRef, ElementType } from "react"; interface PackshotPropsBase { a: string } interface PackshotPropsWeb { b: string } export type Ele ...

Destructuring an object in the find method using TypeScript

I'm running into an issue with object destructuring: Property 'name' does not exist on type 'ItemType | undefined'.ts(2339) App.tsx import "./styles.css"; type ItemType = { id: number; name: string; }; export defaul ...

The mistake occurs when attempting to access a class property generated by a class constructor, resulting in a type error due to reading properties of

I'm having trouble building an Express API in TypeScript using Node.js. I am new to Express and I have been learning Node, JavaScript, and TypeScript since 2022, so I apologize if the question is not too complex. The issue I'm facing is trying to ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Trying out Angular2 service using a fabricated backend

Just a heads up: I know Angular2 is still in alpha and undergoing frequent changes. I am currently working with Angular2 and facing an issue with testing an injectable service that has a dependency on http. I want to test this service using a mock backend ...

Remove the main project from the list of projects to be linted in

Currently in the process of transitioning my Angular application to NX and have successfully created some libraries. I am now looking to execute the nx affected command, such as nx affected:lint, but it is throwing an error: nx run Keira3:lint Oops! Somet ...

Broaden the attributes of an existing function

I am currently developing a Koa web server and I am exploring if it's feasible to include an additional parameter to an already established method on the Koa.app object. const mongoState = await connectToDatabase(); app.use(async (ctx, next) => ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

Error message in Visual Studio 2017: Identical name 'URLs' declared twice in

In our Visual Studio 2017 project, we have multiple TypeScript files that define a URLs class. Each file contains different implementations of the class to change site URLs based on the specific use case: customer/urls.ts namespace Portal { export cl ...