我有data
对象,如下所示派生。它可以具有任意数量的CCD_ 2,每个CCD_。
我正在使用Angular9
,并在TypeScript
中编写以下代码。
const apiResponse = await this.service.geterrors();
const data = apiResponse ['data'];
data =
{
"1": [
{
"ErrorType": "Error-1A",
"Error": "Wrong Password for 1A"
},
{
"ErrorType": "Error-1B",
"Error": "Host not matching"
}
],
"2": [
{
"ErrorType": "Error-2A",
"Error": "Wrong User for 1A"
},
{
"ErrorType": "Error-2B",
"Error": "connectivity issue"
}
],
"3": [
{
"ErrorType": "Error-3A",
"Error": "Wrong version"
}
],
"16": [
{
"ErrorType": "Error-4A",
"Error": "Unknown"
}
]
...
...
}
我想捕获所有计数值,并按降序将它们推送到数组counts
中。
counts = [16, 3, 2, 2, 1, 1];
我想捕获相应的ErrorType
,并将它们推送到数组errorTypes
中。
errorTypes = ['Error-4A', 'Error-3A', 'Error-2B', 'Error-2A', 'Error-1B', 'Error-1A'];
到目前为止,我已经写了以下代码,但它抛出了错误:
const errs = Object.entries(data).map(([k, v]) =>
[v.map(() => +k), v.map(e => e.ErrorType).reverse()]
)
.sort((a, b) => b[0][0] - a[0][0])
;
const [counts, errorTypes] = errs[0]
.map((_, i) => errs.flatMap((_, j) => errs[j][i]))
;
console.log(counts, errorTypes);
上面的代码抛出了2个错误:
TS2339: Property 'map' does not exist on type 'unknown'.
TS2339: Property 'flatMap' does not exist on type 'any[][]'.
您的代码抛出错误,因为typescript不确定它是有一个数字数组还是一个字符串数组,并且它不能映射到那个并集上。
这比你写的更详细,但我无法理解你的代码实际在做什么,所以我只是重写了它。事实证明,我不需要任何高级的打字脚本,尽管我确实为我们的数据结构定义了类型。
interface TypedError {
ErrorType: string;
Error: string;
}
const data: Record<number, TypedError[]> =
{...}
我将错误放入由ErrorType
键入的记录中,该记录包含ErrorType
、count
和group
的编号。然后,我通过比较元素的count
属性对其进行排序。
interface ErrorCount {
count: number;
ErrorType: string;
group: number;
}
const keyedCounts: Record<string, ErrorCount> = {};
Object.entries(data).forEach(
([num, arr]) => arr.forEach(
({ErrorType}) => keyedCounts[ErrorType] = {
count: ( keyedCounts[ErrorType]?.count || 0 ) + 1,
group: parseInt(num),
ErrorType,
}
)
);
const sorted = Object.values(keyedCounts);
sorted.sort((a, b) => b.count - a.count)
从那里,你可以提取你的阵列
const counts = sorted.map( o => o.count );
const names = sorted.map( o => o.ErrorType );
打字游戏场链接