我有两个类似的数组声明:
allFalseOrTrue: any[] = [{'id': -1, 'name': 'All'}, {'id': 0, 'name': 'No'}, {'id': 1, 'name': 'Yes'}];
bothFalseOrTrue: any[] = [{'id': -1, 'name': 'Both'}, {'id': 0, 'name': 'No'}, {'id': 1, 'name': 'Yes'}];
你会建议统一阵列吗?
我的意思是我希望有一些基本的东西,我可以用来构建我的另外两个相似的数组,以避免copypaste。
假设我有源array
或enum
之类的内容,并且只能基于能够构建其他数组的内容。
答案 0 :(得分:2)
如何使用函数创建数组:
type Name = "All" | "Both" | "No" | "Yes";
function createOptions(...names: Name[]) {
return names.map((name, i) => ({ id: i - 1, name }));
}
const all_no_yes = createOptions("All", "No", "Yes");
const both_no_yes = createOptions("Both", "No", "Yes");
或者您可以创建单个数组并过滤到您想要的数组:
const all = [{ id: -1, name: "All" }, { id: -1, name: "Both" }, { id: 0, name: "No" }, { id: 1, name: "Yes" }];
const all_no_yes = all.filter(item => item.name != "Both");
const both_no_yes = all.filter(item => item.name != "All");
另请注意,使用any[]
会使类型模糊,如果您允许推断类型(如上所述,没有类型注释),您将获得具有形状{ id, name }
的项目的数组,这是更好。