仅从其数组中具有true属性的对象与typescript反应

时间:2020-05-28 09:23:40

标签: reactjs typescript

我是打字稿新手。在这里,我有一个几乎没有属性的对象数组,

unseenNodes

现在,我正在尝试

我从两个地方调用此方法graph,在那里我传递了一个变量,该变量将根据其值为我提供数据。

因此,如果变量为false,那么它应该返回我在getConfig方法中当前正在处理的所有数据,如果为true,则它应该返回唯一具有let data = [{ "Id": "1", "Test": true }, { "Id": "2", "Test": true }, { "Id": "1", "Test": true, "ShowAttribute": true }]; // Here, I am trying to get the data const getConfig = (ShowAttribute) => { return <Array<prod>>config?.appConfig?.attributes?.data ?? [] } // this is the structure here I have added only the final object which is data. 属性的对象。

那么,我该如何实现呢?

1 个答案:

答案 0 :(得分:1)

因此,如果变量为false,则它应返回我在getConfig方法中当前正在执行的所有数据,如果为true,则应返回具有ShowAttribute属性的唯一对象。

听起来您想分支:

const getConfig = (ShowAttribute: boolean) => {
    if (ShowAttribute) {
        return data.filter(entry => "ShowAttribute" in entry);
        // Or if you mean the entry's `ShowAttribute` should be `true`:
        // return data.filter(({ShowAttribute}) => ShowAttribute);
    }
    return data; // Or maybe: `return data.slice()` if you want to make a defensive copy
};

......其中data是您要使用的数组(我无法从您的代码中知道它的真实名称; config?.appConfig?.attributes?.data?)。


在评论中您已经问过:

只是一件事,我该怎么添加?为此,如果数据不存在。一个。空数组

假设您的数据来自config?.appConfig?.attributes?.data,您将执行以下操作:

const getConfig = (ShowAttribute: boolean) => {
    const data = config?.appConfig?.attributes?.data ?? []; // <====
    if (ShowAttribute) {
        return data.filter(entry => "ShowAttribute" in entry);
        // Or if you mean the entry's `ShowAttribute` should be `true`:
        // return data.filter(({ShowAttribute}) => ShowAttribute);
    }
    return data; // Or maybe: `return data.slice()` if you want to make a defensive copy
};