如何检查数组对象的属性并将结果为true的元素推入新数组 typescript

huangapple go评论66阅读模式
英文:

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

问题

我有一个对象数组,我需要检查每个对象的“read”属性,如果为true,我需要将整个对象添加到一个新数组中。我尝试了两种方法,都返回错误:“Uncaught TypeError: Cannot read properties of undefined (reading 'push')”。

第一种方法:

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

整个文件:

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>
    );
};
英文:

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 =&gt; {
        if(i.read === true) {
            readArray.push(i)
        };
    });

Second method:

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

Whole file:

import &#39;./Main.css&#39;;
import { useState } from &#39;react&#39;;

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

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

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


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

    return (
        &lt;div&gt;
            main
        &lt;/div&gt;
    );
};

答案1

得分: 1

以下是已翻译的内容:

你遇到的错误是因为在尝试将元素推送到readArray之前,你没有初始化readArray变量。有一个简单的解决方法。你可以在循环之前将readArray初始化为空数组。

let readArray: DocType[] = [];

我已经在你的代码中添加了初始化。

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

希望这对你有所帮助。

英文:

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 &#39;./Main.css&#39;;
import { useState } from &#39;react&#39;;

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

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

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

    return (
        &lt;div&gt;
            main
        &lt;/div&gt;
    );
};

答案2

得分: 0

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

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

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

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

huangapple
  • 本文由 发表于 2023年6月13日 18:30:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76463972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定