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

JavaScript中for循环仅返回单个对象?数组转对象数组求助

解决方案:将日期数组转换为含Day键的对象数组

你当前的代码只创建了单个对象,循环过程中不断覆盖这个对象的Day属性,所以最终只会保留数组最后一个元素的值。要得到目标结果,需要创建一个对象数组,每个元素都是独立的{Day: 日期}对象。

方法1:使用forEach循环构建数组

const months = ["08/31/2022", "09/01/2022", "08/31/2022", "08/31/2022", "08/31/2022", "08/31/2022"];
const result = [];
months.forEach(date => {
  result.push({ Day: date });
});
console.log(result);

方法2:使用map方法(更简洁,推荐React场景)

map方法会遍历数组并返回新的映射数组,非常适合这种场景:

const months = ["08/31/2022", "09/01/2022", "08/31/2022", "08/31/2022", "08/31/2022", "08/31/2022"];
const result = months.map(date => ({ Day: date }));
console.log(result);

最终输出

两种方法都会生成你需要的对象数组:

[
  {"Day": "08/31/2022"},
  {"Day": "09/01/2022"},
  {"Day": "08/31/2022"},
  {"Day": "08/31/2022"},
  {"Day": "08/31/2022"},
  {"Day": "08/31/2022"}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:51:34