如何通过构造函数从数组批量生成指定格式的People对象?
问题解决:将数组映射为指定格式的People对象
原始代码与需求
现有代码
constructor(People) { this.PeopleName = People['Name']; this.PeopleId = People['Id']; this.PeopleGender = People['Gender']; this.Peopleunit = People['unit']; } const Name = ["Ashok", "Payal"]; const Id = ["1", "2"]; const Gender = ["M", "F"];
预期输出
需要将上述数组的值映射,生成指定格式的对象数组,其中unit为固定值234:
[ {Name:'Ashok', Id: '1', Gender: 'M', unit: '234'}, {Name:'Payal', Id: '2', Gender: 'f', unit: '234'} ]
解决方案
首先需要调整构造函数的属性命名,使其与预期输出的字段一致,再通过遍历数组生成实例。
步骤1:修正构造函数
class Person { constructor(personData) { this.Name = personData.Name; this.Id = personData.Id; this.Gender = personData.Gender; this.unit = personData.unit; } }
步骤2:生成目标对象数组
方法一:使用map方法(简洁高效)
利用数组的map方法遍历,根据索引匹配各数组对应值,同时处理Gender的小写转换:
const fixedUnit = '234'; const peopleList = Name.map((name, index) => { return new Person({ Name: name, Id: Id[index], Gender: Gender[index].toLowerCase(), unit: fixedUnit }); }); // 输出结果 console.log(peopleList);
方法二:使用for循环(手动遍历)
如果偏好for循环实现,确保遍历索引正确并将实例推入结果数组:
const fixedUnit = '234'; const peopleList = []; for (let i = 0; i < Name.length; i++) { const person = new Person({ Name: Name[i], Id: Id[i], Gender: Gender[i].toLowerCase(), unit: fixedUnit }); peopleList.push(person); } // 输出结果 console.log(peopleList);
关键注意事项
- 构造函数的属性名必须与预期输出的字段完全匹配,避免出现
PeopleName这类冗余命名。 - 预期输出中第二个对象的
Gender为小写,需要通过toLowerCase()方法转换原数组的值。 - 确保
Name、Id、Gender三个数组长度一致,防止索引越界导致的错误。
内容的提问来源于stack exchange,提问作者Anvi Creations
相关产品推荐
相关产品推荐

