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