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

如何将两个索引对应的数组转换为指定结构的对象数组

问题原因

你当前的代码逻辑是将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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:27:06