【发布时间】:2019-11-03 13:30:24
【问题描述】:
我正在尝试创建一个可以在打字稿中展平嵌套数组的函数。
到目前为止,我有这个:
function flattenArrayByKey<T, TProp extends keyof T>(array: T[], prop: TProp): T[TProp] {
return array.reduce((arr: T[TProp], item: T) => [...arr, ...(item[prop] || [])], []);
}
那里的array.reduce 完全符合我的要求,但我无法让泛型与我想要的完美配合。我认为我的问题是item[prop] 返回any,因为它无法推断item[prop] 返回T[TProp]。
我的目标是一个可以采用这种结构的函数:
interface MyInterface {
arrayProperty: string[];
anotherArray: number[]
someNumber: number;
}
const objectsWithNestedProperties: MyInterface[] = [
{
arrayProperty: ['hello', 'world'],
anotherArray: [1, 2],
someNumber: 1,
},
{
arrayProperty: ['nice', 'to'],
anotherArray: [3, 4],
someNumber: 2,
},
{
arrayProperty: ['meet', 'you'],
anotherArray: [5, 6],
someNumber: 3,
},
];
并返回一个包含所有嵌套数组内容的数组。
const result = flattenArrayByKey(objectsWithNestedProperties, 'arrayProperty');
result 应该看起来像 ['hello', 'world', 'nice', 'to', 'meet', 'you']
基本上我正在从 C# 的 linq 中寻找 SelectMany。
【问题讨论】:
-
Array.flat()已经在一些现代浏览器中工作 -
@Kokodoko 不允许我指定要展平的嵌套数组。
标签: arrays typescript generics flatten