首页 > 解决方案 > 查找对象中的前 2 个值不起作用 - Angular 6

问题描述

我试图在数组中的对象中查找前 2 个值,但它不起作用。我已经这样做了,但是对于一些不在数组中的平均值并且它可以工作,但是当我遍历一些结果并尝试为每个结果找到前 2 个值时,它会显示一个错误......

这就是我的代码的样子:

// Models:

export class Results {
    public capture_at: string;
    public comment: string;
    public emotion_average: EmotionAverage;
    public location: string;
    public os_type: string;
    public sdk_value: string;
    public user: string;
    public uuid: string;
    public topTwo: TopTwo;
}

export class TopTwo {
    public label: string;
    public value: number;
}

export class EmotionAverage {
    public anger: number;
    public contempt: number;
    public disgust: number;
    public engagement: number;
    public fear: number;
    public joy: number;
    public sadness: number;
    public surprise: number;
    public valence: number;
}

当我在组件内获取数据时的代码:

for (const emotion of this.activeCampaignModel.video.emotion.results) {
    emotion.topTwo = Object
    .entries(emotion.emotion_average)
    .sort(({ 1: a }, { 1: b }) => b - a)
    .slice(0, 2)
    .map(([label, value]) => ({ label, value }));
}

我得到的错误是:

输入'{标签:字符串;值:任何;}[]' 不可分配给类型 'TopTwo'。'{ label: string; 类型中缺少属性 'label' 值:任何;}[]'。

提前致谢

标签: javascriptangularangular6

解决方案


你能试着改变你的地图吗

.map(([label, value]) => ({ label, value }));

为此?

.map((label, value) => ({ label, value }));

推荐阅读