簡體   English   中英

在 Javascript 中的 JSON 數組中將日期添加到日期

[英]Adding days to a Date from an Array of JSON in Javascript

我對 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 是字符串而不是數字。 您應該將其包裝在對parseInt的調用中。

例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM