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