【问题标题】:Convert a JSON to a required format in type script在类型脚本中将 JSON 转换为所需的格式
【发布时间】:2020-10-22 18:58:18
【问题描述】:

我对 Angualr 6 和类型脚本非常陌生。从后端 API 调用我得到以下格式的数据。

> res = [{
>     "metadata": {
>         "lastGpSyncTime": "2000-11-21T16:07:53",
>         "dataFromDB": true
>     },
>     "noGoalSelectionReport": {
>         "userCount": 0
>     },
>     "oneGoalSelectionReport": {
>         "userCount": 237
>     },
>     "twoGoalSelectionReport": {
>         "userCount": 176
>     },
>     "threeGoalSelectionReport": {
>         "userCount": 17
>     },
>     "registeredCount": 547 }];

我需要将其转换为这样的格式,以便可以在条形图中显示它。条形图需要以下格式。

[{
  "goalName": "No Goal",
  "userCount": 0
}, {
  "goalName": "One Goal",
  "userCount": 237
}, {
  "goalName": "Two Goals",
  "userCount": 176
}, {
  "goalName": "Three Goals",
  "userCount": 17
}];

如何使用类型脚本来做到这一点。

【问题讨论】:

  • Typescript 或多或少只是类型注释。它本身不能转换 json 格式。但是Javascript可以。你应该通过简单的 js 语句来处理它。

标签: angular typescript angular6 angular5


【解决方案1】:

怎么样?

    formatData(res): { goalName: string, userCount: number }[] {

        const data = res[0];
        const groupNames = Object.keys(data);

        const formattedData = [];

        groupNames.forEach(groupName => {
            if (groupName !== 'metadata') {

                // Add Space before capital letter and remove SelectionReport
                let goalName = groupName.replace('SelectionReport', '').replace(/([A-Z])/g, ' $1').trim();

                // Capitalize first letter
                goalName = goalName.charAt(0).toUpperCase() + goalName.slice(1);

                const dataGroupFormatted = {
                    goalName,
                    userCount: data[groupName].userCount
                };

                formattedData.push(dataGroupFormatted);
            }
        });

        return formattedData;

    }

Typescript 的强大之处在于定义类型,例如,您的条形图需要一个特定类型,该类型是一个包含goalName 和userCount 的对象数组。您可以通过添加更多类型(例如 res 的输入类型)来改进我的答案。

【讨论】:

    【解决方案2】:

    一个简单的例子

        var result = Object.keys(this.res[0]);
        let temp = [];
        for (let i = 0; i < result.length; i++) {
          if (result[i] !== "metadata" && result[i] !== "registeredCount") {
            
            temp.push({
              userCount: this.res[0][result[i]].userCount,
              goalName:
                result[i]
                  .toUpperCase()
                  .charAt(0) +
                result[i]
                  .replace("SelectionReport", "")
                  .replace(/([A-Z])/g, " $1")
                  .trim()
                  .slice(1)
            });
          }
        }
        console.log(temp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2014-01-05
      • 2016-09-20
      • 1970-01-01
      • 2014-09-14
      • 2021-12-26
      相关资源
      最近更新 更多