展平嵌套对象打字稿

flattening nested objects typescript

我想在我的控制器中展平嵌套对象(Loopback 和 Typescript 的新功能)

这是我的模型:

export class SampleModel {
  id: number;
  code: number;
  guide?: string;
  gradeData?: string;
}

这是一个示例对象:

{
  "id": 1,
  "code": 12345,
  "guide": "Guide for 2021",
  "gradeData": {
    "en": "Eng grade",
    "de": "Ger grade"
  }
}

这是我的控制器:

// returns an array of SampleModel objects
@get('/guides')
async find(
@param.query.string('lang') lang: string,
@param.filter(SampleModel) filter?: Filter<SampleModel>
): Promise<SampleModel[]> {
return this.sampleModelRepository.find(filter); //this returns Promise<SampleModel[]>
}

我想根据 lang 稍微调整一下这个响应。例如:如果 lang = en 我希望响应看起来像

[
  {
    "id": 1,
    "code": 12345,
    "guide": "Guide for 2021",
    "gradeData": "Eng grade"
  }
]

是这样的吗? 当然,您需要使语言代码动态化

[{
  "id": 1,
  "code": 12345,
  "guide": "Guide for 2021",
  "gradeData": {
    "en": "Eng grade",
    "de": "Ger grade"
  }
}].map(e=>{
    e.gradeData = e.gradeData["en"];
    return e;
})

返回对象:

[
    {
        "id": 1,
        "code": 12345,
        "guide": "Guide for 2021",
        "gradeData": "Eng grade"
    }
]

多亏了@Firewizz,我才能够做到这一点。这是我更新的控制器:

  // returns an array of SampleModel objects
  @get("/guides")
  async find(
    @param.query.string("lang") lang: string,
    @param.filter(SampleModel) filter?: Filter<SampleModel>
  ): Promise<SampleModel[]> {
    const res = this.sampleModelRepository.find(filter); //this returns Promise<SampleModel[]>
    if (lang != null) {
      (await res).map((e) => {
        if (e.gradeData != null && e.gradeData.hasOwnProperty(lang)) {
          e.gradeData = new Map(Object.entries(e.gradeData)).get(locale);
          // not sure why this is required but when I tried
          // `e.gradeData = e.gradeData[locale];`
          // I get compilation error " Element implicity has an 'any' type because index expression is not of type 'number' " maybe because gradeData is defined as a String but when I do
          // console.log(typeof e.gradeData)
          // I get object

          // I also tried
          // `e.gradeData = JSON.parse(e.gradeData)[locale];`
          // I get " SyntaxError: Unexpected token o in JSON at position 1 " and that could be because it's already an object

          // I then tried
          // `e.gradeData = JSON.parse(JSON.stringify(e.gradeData))[locale];`
          // this also works but I think converting this to a map as a workaround is better
        }
        return e;
      });
    }

    return res;
  }