0

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:

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>
    );
};
Papgooner
  • 13
  • 5
  • Does this answer your question? [javascript filter array multiple conditions](https://stackoverflow.com/questions/31831651/javascript-filter-array-multiple-conditions) – Hardik Vaghani Jun 13 '23 at 11:04

2 Answers2

1

The error you're encountering is because you haven't initialized the readArray variable before trying to push elements into it. There is easy fix. You can initialize readArray as an empty array before the loop.

let readArray: DocType[] = [];

I add initialization 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>
    );
};
Daniel Vágner
  • 538
  • 3
  • 19
0

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

const readArray = useMemo(() => {
  return docList.filter(doc => doc.read)
}, [docList])
wonderflame
  • 6,759
  • 1
  • 1
  • 17