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

如何将对象数组映射后按指定格式生成目标全名?

解决方案

要得到"Sir Anderson, Martin"的格式,你需要放弃原数组的遍历顺序,精准提取对应字段值后按目标规则拼接,以下是两种可行方法:

方法一:直接定位字段拼接

针对固定字段场景,直接找到对应字段的取值后组合:

// 从数组中匹配对应字段的gqlName,再从obj中取值
const title = _.get(this.obj, `${this.dtoName}.${this.selectsUsers.find(item => item.column === 'Title').gqlName}`);
const lastname = _.get(this.obj, `${this.dtoName}.${this.selectsUsers.find(item => item.column === 'Lastname').gqlName}`);
const name = _.get(this.obj, `${this.dtoName}.${this.selectsUsers.find(item => item.column === 'Name').gqlName}`);

// 按目标格式拼接
let pathView = `${title} ${lastname}, ${name}`;

这种方式逻辑直观,适合字段固定不变的场景,若担心字段不存在,可给_.get添加默认值,比如_.get(..., '')避免出现undefined。

方法二:重排数组后处理

如果需要更灵活的顺序调整,可先按目标顺序重组数组,再通过reduce拼接:

// 定义目标字段顺序
const targetColumnOrder = ['Title', 'Lastname', 'Name'];
// 按目标顺序生成新数组
const sortedFields = targetColumnOrder.map(col => this.selectsUsers.find(item => item.column === col));

// 按规则拼接值
let pathView = sortedFields.reduce((result, item, index) => {
  const value = _.get(this.obj, `${this.dtoName}.${item.gqlName}`);
  if (index === 0) {
    return value;
  } else if (index === 1) {
    return `${result} ${value}`;
  } else {
    return `${result}, ${value}`;
  }
}, '');

后续若要调整格式顺序,只需修改targetColumnOrder即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:01:27