将嵌套数组转换为嵌套对象

Convert nested array to nested object

我正在使用 typeorm 从 DB 获取数据,我想列出我的所有问题以及每个问题的最后状态。

我的数据库有 2 个表:Issues 和 IssueStatus 进入 IssueStatus 我会保存每一个状态变化和关于如何解决 Issue 的评论。

我的代码:

var issues = await issuesRepository
    .createQueryBuilder('issue')
    .select(['issue', 'history.status'])
    .innerJoin('issue.history', 'history')
    .leftJoin(
      'issue.history',
      'history2',
      'history.date < history2.date OR (history.date = history2.date AND history.id < history2.id)'
    )
    .where('history2.id IS NULL')
    .getMany();

我得到这个结果:

{
    "id": "5ff86c81-a202-4211-84f4-afe2d5c0fc0d",
    "cod": 1,
    "opendate": "2020-12-08T13:18:55.683Z",
    "closedate": null,
    "type": "systems",
    "subtype": "avance",
    "description": "first test",
    "mailto": "sustentacao@bonnjur.com.br",
    "hostname": "dskcwbti02",
    "username": "glenn.veloso",
    "solution": null,
    "supportby": null,
    "history": [
      {
        "status": 0
      }
    ]
  }

但我想要这个:

{
    "id": "5ff86c81-a202-4211-84f4-afe2d5c0fc0d",
    "cod": 1,
    "opendate": "2020-12-08T13:18:55.683Z",
    "closedate": null,
    "type": "systems",
    "subtype": "avance",
    "description": "first test",
    "mailto": "sustentacao@bonnjur.com.br",
    "hostname": "dskcwbti02",
    "username": "glenn.veloso",
    "solution": null,
    "supportby": null,
    "status": 0
  }

您可以像下面那样制作 smth,但是您需要用 select 中的别名覆盖所有必填字段:

var issues = await issuesRepository
    .createQueryBuilder('issue')
    .select(['issue', 'history.status AS status']) // <- changes here
    .innerJoin('issue.history', 'history')
    .leftJoin(
      'issue.history',
      'history2',
      'history.date < history2.date OR (history.date = history2.date AND history.id < history2.id)'
    )
    .where('history2.id IS NULL')
    .getRawMany(); // <- changes here

我的意思是

you will need to overwrite all required fields with aliases in select

.select([
  'issue.id AS id',
  'issue.cod AS cod',
  'issue.opendate AS opendate',
...
...
...
  'issue.solution AS solution',
  'issue.supportby AS supportby',
  'history.status AS status'
])