Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check a property of an array of objects and push the true results to a new array typescript

I have an array of objects, I need to check each objects ‘read’ property and if true I need the whole object to be added to a new array. I tried a couple of methods, both return the error: Uncaught TypeError: Cannot read properties of undefined (reading ‘push’).

First method:

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

Second method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Whole file:

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)
        };
    });


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

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

>Solution :

Instead of pushing, just filter. Also, consider using useMemo for the readArray:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading