【问题标题】:Adding days to a Date from an Array of JSON in Javascript在 Javascript 中从 JSON 数组向日期添加日期
【发布时间】:2021-05-03 18:37:44
【问题描述】:

我在 MongoDB 上的操作得到以下结果。

这是订单的结果:

const orders = [{
    "price": 20200,
    "order_number": "19",
    "items": [{
      "product": {
        "_id": "60373f6e93af7d3e3239b21e",
        "title": "bb Set",
        "process_time": "10"
      },
      "quantity": 1,
      "price": 19000,
      "shipping": 1200,
    }],
    "createdAt": "2021-04-25T12:27:07.985Z",
  },
  {
    "price": 100,
    "order_number": "20",
    "items": [{
      "product": {
        "_id": "60373f6e93af7d3e3239b2op",
        "title": "Iron Set",
        "process_time": "12"
      },
      "quantity": 1,
      "price": 90,
      "shipping": 10,
    }],
    "createdAt": "2021-04-25T12:27:07.985Z",
  }
]

我想将process_time 的天数添加到createdAt 字段并将计算的日期写回process_time。

我就是这样做的:

function getDeliveryTime(process_time, order_date) {
  let delivery_time = order_date + 1000 * 3600 * 24 * process_time
  return new Date(delivery_time).toLocaleDateString()
}

function updateProcess_time(orders) {
  for (const order of orders) {
    const createdOrder = order.createdAt
    for (const item of order.items) {
      item.product.process_time = getDeliveryTime(parseInt(item.product.process_time), new Date(createdOrder).getTime())
      console.log(item.product.process_time) // I get the value of the process_time at first iteration but get the value of calculated date in the 2nd iteration.
    }
    
  }
  return orders
}

问题是一些日期没有计算,只有少数返回计算的日期。但大多数我得到process_time: "Invalid Date"。 我认为问题在于它没有等到所有计算完成后才返回订单。

【问题讨论】:

  • 问题可能是 process_time 不是数字的字符串表示形式,或者 createdAt 不是 ISO 8601 日期。也许您的 MongoDB 返回空值?
  • 我更多的是考虑如何更改代码,以便它等到所有计算完成后再返回。
  • @myadsmail ,将计算部分转移到另一个函数中并使用 aync await 等待计算完成
  • 我不知道在这段代码中在哪里使用 async/await。
  • 更改了答案,但仍然没有得到答案。

标签: javascript node.js arrays mongodb


【解决方案1】:

process_time 是字符串而不是数字。您应该将其封装在对 parseInt 的调用中。

例如

getDeliveryTime(parseInt(item.product.process_time), new Date(createdOrder).getTime())

【讨论】:

  • 不一定:2 * '3' === 6
  • 啊,是的,我正在使用不同的值进行测试。它仍然可能是问题
  • 此日期或日期不是有效的 ISO 8601 日期
  • 我更改为Int,但仍然出现错误。因为在循环内部它不会改变 process_time。
  • 虽然我改了答案。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多