typescript 如何在JSON中实现接口

55ooxyrt  于 2023-01-06  发布在  TypeScript
关注(0)|答案(1)|浏览(112)

我进入数据库并获取“topics”的“percent_values”,然后求出它们的平均值,返回给我的JSON如下所示,包含“sector_name”和平均值。但如果没有某个主题的“percent_value”,则不会返回该部门。我想返回mean = 0的部门。我该怎么做?
他们给了我一个技巧,让我使用主题的接口和值的常量 的主题已经等于0,我创建了它,但我不知道如何准确地实现它...我怎么能这样做呢?

Json

// JSON that returns to me
{
  "Sector1": 4,
  "Sector2": 24,
  "Sector3": 2.5,
  "Sector4": 9.5,
  "Sector6": 74,
  "Total": 19
}

// JSON that I want
{
  "Sector1": 4,
  "Sector2": 24,
  "Sector3": 2.5,
  "Sector4": 9.5,
  "Sector5": 0,
  "Sector6": 74,
  "Total": 19
}

接口和缺点

export interface ISectorTopics {
    'Sector1': {
        'topic1': number | null,
        'topic2': number | null,
        'topic3': number | null,
        'topic4': number | null,
        'topic5': number | null
    },
    'Sector2': {
        'topic1': number | null,
        'topic2': number | null
    },
    'Sector3': {
        'topic1': number | null,
        'topic2': number | null,
        'topic3': number | null,
        'topic4': number | null
    },
    'Sector4': {
        'topic1': number | null,
        'topic2': number | null,
        'topic3': number | null,
        'topic4': number | null
    },
    'Sector5': {
        'topic1': number | null,
        'topic2': number | null,
        'topic3': number | null
    },
    'Sector6': {
        'topic1': number | null,
        'topic2': number | null,
        'topic3': number | null
    }
};

export const sectorTopicsDefaultValues : ISectorTopics = {
    'Sector1': {
        'topic1': 0,
        'topic2': 0,
        'topic3': 0,
        'topic4': 0,
        'topic5': 0
    },
    'Sector2': {
        'topic1': 0,
        'topic2': 0
    },
    'Sector3': {
        'topic1': 0,
        'topic2': 0,
        'topic3': 0,
        'topic4': 0
    },
    'Sector4': {
        'topic1': 0,
        'topic2': 0,
        'topic3': 0,
        'topic4': 0
    },
    'Sector5': {
        'topic1': 0,
        'topic2': 0,
        'topic3': 0
    },
    'Sector6': {
        'topic1': 0,
        'topic2': 0,
        'topic3': 0
    }
}

服务

@Injectable()
export class MyService {
  constructor(private dataSource: DataSource) {}

  myRepository = this.dataSource.getRepository(data);

  async getAll(year: number, month: number) {
    let datas;
    await this.myRepository
      .find({
        relations: {
          topic: {
            sector: true
          }
        },
        select: {
          month_reference: true,
          year_reference: true,
          percent_data: true,
          topic: {
            topic_name: true,
            sector: {
              sector_name: true
            }
          }
        },
        where: {
          month_reference: month,
          year_reference: year
        }
      })
      .then((response) => datas = response);

      const dataObj = {}
      const sectors = {};

      datas.forEach((data) => {
        if (!sectors[data.topic.sector.sector_name]) {
          sectors[data.topic.sector.sector_name] = [];
        }
        if (data.month_reference == month && data.year_reference == year) {
          let value;

          data.percent_value ? value = data.percent_value : 0;

          sectors[data.topic.sector.sector_name].push({
            topic_name: data.topic.topic_name,
            percent_value: value,
          });
        };
      });

      // Calculate the Total Average data per Sector
      const sectorEntries = Object.entries(sectors); 
      
      sectorEntries.forEach(([sectorName, sectorArray]) => {  
        const sum = (<any>sectorArray).reduce((accumulator, currentdata) => {
          return accumulator + currentdata.percent_values;
        }, 0);
        
        const sectorAverage = sum / (<any>sectorArray).length;
    
        sectorAverage ? dataObj[sectorName] = sectorAverage : dataObj[sectorName] = 0;
      })
      
      // Calculate the Total Average data
      const averageSectordatas = Object.values(dataObj);
      const averageSum = averageSectordatas.reduce((accumulator, currentdata) => {
        return (+<any>accumulator) + (+<any>currentdata);
      }, 0);

      const averageTotal = (+<any>averageSum) / averageSectordatas.length;

      averageTotal ? dataObj["Total"] = +averageTotal.toFixed(2) : dataObj["averageTotal"] = 0;

      return data;
  }
}
e4yzc0pl

e4yzc0pl1#

如果某个扇区的主题没有百分比值,则要返回平均值为0的扇区,您需要修改代码以包含针对这种情况的检查。
下面是一个示例,说明如何修改代码来实现这一点

$sectors = [];

// Iterate through the topics
foreach ($topics as $topic) {
  $sector_name = $topic['sector_name'];
  if (isset($sectors[$sector_name])) {
    $sectors[$sector_name]['count']++;
    $sectors[$sector_name]['sum'] += $topic['percent_value'];
  } else {
    $sectors[$sector_name] = [
      'count' => 1,
      'sum' => $topic['percent_value']
    ];
  }
}

// Calculate the mean for each sector
foreach ($sectors as $sector_name => &$sector) {
  if ($sector['count'] > 0) {
    $sector['mean'] = $sector['sum'] / $sector['count'];
  } else {
    $sector['mean'] = 0;
  }
}

// Return the sectors array
return $sectors;

此代码迭代主题并跟踪每个扇区的百分比值的总和和计数。然后,它通过将总和除以计数来计算每个扇区的平均值。如果计数为0(表示该扇区没有百分比值),则平均值设置为0。

相关问题