如何将两个索引对应的数组转换为指定结构的对象数组
问题原因
你当前的代码逻辑是将descriptionList的元素作为对象键,statusList对应位置元素作为值,最终生成的是扁平的键值对对象,和你需要的「包含多个固定属性对象的数组」结构不符。
调整后的实现代码
const descriptionList = ["First", "Second", "Last"]; const statusList = ["Jon", "Jim", "Den"]; // 初始化符合目标结构的结果,subtasks字段初始为数组类型 const result = { subtasks: [] }; // 遍历过程中逐个组装subtask对象,推入subtasks数组 descriptionList.forEach((desc, index) => { result.subtasks.push({ description: desc, status: statusList[index] }); }); console.log(result);
兼容异常场景(可选)
如果两个数组长度可能不一致,建议取两者的最小长度遍历,避免生成属性值为undefined的无效对象:
const minLen = Math.min(descriptionList.length, statusList.length); const result = { subtasks: [] }; for(let i = 0; i < minLen; i++) { result.subtasks.push({ description: descriptionList[i], status: statusList[i] }); }
内容的提问来源于stack exchange,提问作者Nina
相关产品推荐
相关产品推荐

