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

TypeScript中如何提取数组指定字段生成键值对存入新数组?

解决TypeScript数组提取键值对的问题

嘿,别担心,作为新手遇到这种数组遍历的问题太正常啦!我来帮你理清楚问题出在哪,以及怎么解决~

你的代码问题所在

你在createNamePlusSpouseArray里的forEach用法出错了:

  • 你把回调参数命名为name,但它其实是participantArray里的整个参与者对象(比如{ "name": "Cristina", "email": "cristina@gmail", ... }),不是数组索引。
  • 所以this.participantArray[name]相当于用字符串(比如"Cristina")去数组里取元素,这显然会得到undefined,因为数组是按数字索引访问的。

修正后的实现

根据你的需求(提取name为键、yourPerson为值存入新数组),这里有两种常见的实现方式,你可以根据实际需求选:

方式1:新数组包含单个键值对对象

如果你希望namePlusSpouseArray是一个数组,每个元素是独立的键值对对象(比如[{ "Cristina": "Richard" }]),可以这么写:

participantArray: Array<{name: string; email: string; yourPerson: string; spouseEmail: string}> = [];
namePlusSpouseArray: Array<{[key: string]: string}> = [];

submitParticipant() {
  this.participantArray.push(this.participantForm.value);
  console.log(this.participantArray);
  this.createNamePlusSpouseArray();
}

createNamePlusSpouseArray() {
  // 先清空数组,避免重复添加之前的元素(可选,根据你的业务逻辑调整)
  this.namePlusSpouseArray = [];
  
  this.participantArray.forEach(participant => {
    // 直接从当前遍历的对象里提取需要的属性
    const key = participant.name;
    const value = participant.yourPerson;
    // 构建键值对对象并推入新数组
    this.namePlusSpouseArray.push({ [key]: value });
    console.log(this.namePlusSpouseArray);
  });
}

方式2:生成一个单一的键值对映射对象

如果你的需求是把所有参与者的name和yourPerson整合到一个对象里(比如{ "Cristina": "Richard" }),用reduce会更简洁:

participantArray: Array<{name: string; email: string; yourPerson: string; spouseEmail: string}> = [];
// 把类型改成对象,存储键值对映射
namePlusSpouseMap: {[key: string]: string} = {};

submitParticipant() {
  this.participantArray.push(this.participantForm.value);
  console.log(this.participantArray);
  this.createNamePlusSpouseMap();
}

createNamePlusSpouseMap() {
  this.namePlusSpouseMap = this.participantArray.reduce((map, participant) => {
    map[participant.name] = participant.yourPerson;
    return map;
  }, {} as {[key: string]: string});
  
  console.log(this.namePlusSpouseMap); // 输出: { "Cristina": "Richard" }
}

新手小提示

  • 用forEach遍历数组时,回调的第一个参数永远是当前数组元素,第二个参数才是索引,别搞混啦~
  • 每次生成新数组/映射前,记得清空目标变量,不然每次调用submitParticipant都会重复添加旧数据,导致结果不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:02:46