【问题标题】:How to format a date that is a value in an array of objects如何格式化作为对象数组中的值的日期
【发布时间】:2025-12-09 08:30:01
【问题描述】:

我有一个对象数组:

var exerciseLog = [{“date”:“2019-07-02T21:18:48.946Z”,“description”:“pull ups”,“duration”:“90”},{“date”:“2019-07-02T21:22:30.395Z”,“description”:“push ups”,“duration”:“90”},{“date”:“2019-07-02T22:19:37.790Z”,“description”:“push ups”,“duration”:“50”}]

我想格式化日期以排除时间,以便日期显示为“YYYY-MM-DD”或“YYYY/MM/DD”。

我试过 map、forEach、slice、splice。

exerciseLog = exerciseLog.forEach(x => x.date.toLocaleDateString());

在代码的相关部分不起作用:

app.get("/api/exercise/log", function (req, res) {
    var userId = req.query.userId; 
    var from = req.query.from ? new Date(req.query.from) : new Date("1970-01-01");
    var to = req.query.to ? new Date(req.query.to) : new Date();

    User.findById(userId, function (err, doc) {
      if (!doc) {
        res.send({ "error": "userId not found" });
      } else {
        var exerciseLog = doc.exercises.sort((a, b) => a.date.getTime() - b.date.getTime())
          .filter(x => x.date >= from && x.date <= to);
        var limit = !isNaN(req.query.limit) ? req.query.limit : exerciseLog.length;
        exerciseLog = exerciseLog.slice(0, limit);
        exerciseLog = exerciseLog.forEach(x => x.date.toLocaleDateString());
        res.send({ "username": doc.username, "Exercise Count": exerciseLog.length, "Exercise Log": exerciseLog });
      }
    });
  });

错误:

events.js:160
6:59 PM
      throw er; // Unhandled 'error' event
6:59 PM
      ^
6:59 PM
6:59 PM
TypeError: Cannot read property 'length' of undefined
6:59 PM
Jump to
at /app/server.js:138:77
6:59 PM
    at /rbd/pnpm-volume/52232b84-c31b-4266-9261-f25b6365dff7/node_modules/.registry.npmjs.org/mongoose/5.6.2/node_modules/mongoose/lib/model.js:4846:16
6:59 PM
    at /rbd/pnpm-volume/52232b84-c31b-4266-9261-f25b6365dff7/node_modules/.registry.npmjs.org/mongoose/5.6.2/node_modules/mongoose/lib/query.js:4283:12
6:59 PM
    at process.nextTick (/rbd/pnpm-volume/52232b84-c31b-4266-9261-f25b6365dff7/node_modules/.registry.npmjs.org/mongoose/5.6.2/node_modules/mongoose/lib/query.js:2776:28)
6:59 PM
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
6:59 PM
    at process._tickCallback (internal/process/next_tick.js:104:9)

哪个指向这条线:

var limit = !isNaN(req.query.limit) ? req.query.limit : exerciseLog.length;

但如果我删除带有 forEach 行的代码,我没有错误。

完整代码https://glitch.com/edit/#!/swamp-liquid?path=server.js:138:53.

【问题讨论】:

  • 您当前输入的语法无效。尽量避免在编程中使用花引号,它们经常会产生问题
  • @CertainPerformance?我不确定你是什么意思?在我的问题中,当数组作为来自我的数据库的响应发送时,它是如何显示的,并且一切正常,除了我希望格式化来自数据库日期的响应。
  • 只需尝试按顶部的“运行代码 sn-p” - 您发布的代码会引发语法错误。
  • 好的,我明白你在说什么。花引号不在我的代码中,它们是通过复制和粘贴到达那里的,我没有注意到它们粘贴为花引号。在我的代码中,它们是常规引号。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您的错误是因为您将返回值从Array.prototype.forEach 分配给exerciseLog

Array.prototype.forEach 不返回任何内容。

你想使用Array.prototype.map

exerciseLog = exerciseLog.map(x =&gt; x.date.toLocaleDateString());

【讨论】:

    【解决方案2】:

    @Miles Grover 和 @BlueWater86 感谢您的帮助。我之前尝试过map,但它不起作用,但现在可以了。

    exerciseLog = exerciseLog.map(x => x.date.toLocaleDateString());
    

    只返回格式化的日期,所以我必须这样做以保留其余的对象信息:

    exerciseLog = exerciseLog.map(x => "description: " + x.description + ", duration: " + x.duration + ", date: " + x.date.toLocaleDateString());
    

    【讨论】:

      【解决方案3】:
      exerciseLog = exerciseLog.forEach(x => x.date.toLocaleDateString());
      

      forEach() 不返回任何内容,因此您将 exerciseLog 设置为 null 或未定义。如果您改用map(),该行将根据您传递给map() 的函数中返回的内容将exerciseLog 设置为一个新数组。

      下一个问题是原始代码 sn-p 中的引号是大引号 - 不确定它来自哪里,但除非是单引号或双直引号,否则不会有任何效果。

      我认为最后一个问题是 x.date 已经是日期字符串,而不是 Date 对象,因此 toLocaleDateString() 将无法处理它。您可以只使用x.date,或者如果您确实需要将日期转换为不同的语言环境,您可以使用new Date(x.date).toLocaleDateString()

      【讨论】: