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
相关产品推荐
相关产品推荐

