You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript/NestJS:从数据库查询结果提取结构化对象

问题

我通过外部API执行SQL查询获取用户数据,返回结果是一组字段形式的匹配实体,格式如下:

[
  { IsNull: false, Name: 'Key', Value: '897', Values: null },
  { IsNull: false, Name: 'FirstName', Value: 'User', Values: null },
  { IsNull: false, Name: 'LastName', Value: 'Portal', Values: null },
  {
    IsNull: false,
    Name: 'Email',
    Value: 'some@email.com',
    Values: null
  },
  { IsNull: true, Name: 'Salutation', Value: null, Values: null },
  { IsNull: false, Name: 'Type', Value: '2', Values: null },
  {
    IsNull: false,
    Name: 'LastLoggedDate',
    Value: '2022-12-01 15:24:03',
    Values: null
  }
]

我希望把该响应转换成简洁对象,例如:{ email: 'some@email', firstName: 'User', lastName: 'Portal' }。最初采用以下实现方式,但字段较多时过于繁琐,想找更简便的方法:

let userRawEntity = queryResult.data.Entities[0].Fields;
const userEmail = userRawEntity.filter((obj) => { return obj.Name === 'Email' });
const userFirstName = userRawEntity.filter((obj) => { return obj.Name === 'FirstName' });
const userLastName = userRawEntity.filter((obj) => { return obj.Name === 'LastName' });

return { email: userEmail[0].Value, firstName: userFirstName[0].Value, lastName: userLastName[0].Value };
优化后的解决方案

编辑补充:最终优化后的可行方案如下,感谢帮助 :)

if (queryResult.data.TotalEntityCount > 0) {
  let user: {[key: string]: string | null } = {}
  let userRawEntity = queryResult.data.Entities[0].Fields;

  userRawEntity.forEach(data => user[data.Name] = data.Value);

  return { email: user.Email, currency: user.Currency } as JwtPayload;
}

内容的提问来源于stack exchange,提问作者dejwus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:55:17