仅从数组中获取该对象,该数组在 React with TypeScript 中具有属性 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.

现在,我正在尝试是

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

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

那么,我怎样才能做到这一点呢?

因此,如果变量为 false,那么它应该返回我当前在方法 getConfig 中执行的所有数据,如果它是真的,那么它应该返回唯一具有 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
};

最新更新