如何在对象数组中查找日期?

时间:2019-05-15 17:38:15

标签: javascript arrays object

我有一个对象数组,它包含一些数据时间值。如何找到带有“日期”的对象键并将值隐式转换为时刻日期时间?

const old = [
    {name: "Ann", startDate: "2014-11-12T07:45:07.753", endDate: "2014-11-13T07:45:07.753"},
    {name: "Ben", startDate: "2014-11-12T07:45:07.753", endDate: "2014-11-13T07:45:07.753"}
]

首先,我想检查对象键是否具有字符串“ Date”,然后它将对象值转换为moment(value).format(“ YYYY-MM-DD h:mm:ss a”)< / p>

const new = [
    {name: "Ann", startDate: "2014-11-12 7:45:07am", endDate: "2014-11-13 7:45:07 am"},
    {name: "Ben", startDate: "2014-11-12 7:45:07am", endDate: "2014-11-13 7:45:07 am"}
]

2 个答案:

答案 0 :(得分:1)

您需要做的就是遍历数组,然后对象值并在键字符串包含Date的情况下更新它们,如您建议使用indexOf函数的条件

const old = [
    {name: "Ann", startDate: "2014-11-12T07:45:07.753", endDate: "2014-11-13T07:45:07.753"},
    {name: "Ben", startDate: "2014-11-12T07:45:07.753", endDate: "2014-11-13T07:45:07.753"}
]

const res = old.map(obj => {
   return Object.assign({}, ...Object.keys(obj).map((key) => {
      if(key.indexOf("Date") > -1) {
        return {[key]: moment(obj[key]).format("YYYY-MM-DD h:mm:ss a")}
      }else {
        return {[key]: obj[key]}
      }
   }))
})
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

答案 1 :(得分:0)

您可以使用moment.isValid来检查日期是否有效(因为您已经在使用momentjs):

const old = [{ name: "Ann", startDate: "2014-11-12T07:45:07.753", endDate: "2014-11-13T07:45:07.753" }, { name: "Ben", startDate: "2014-11-12T07:45:07.753", endDate: "2014-11-13T07:45:07.753" } ]

let result = old.map(o => {
  Object.keys(o).forEach(k => {
    let d = moment(new Date(o[k]))
    if(d.isValid()) o[k] = moment(d).format("YYYY-MM-DD hh:mm:ss a")
  })
})

console.log(old)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

然后,您将通过map映射到对象键,并针对每个键检查它们是否指向有效日期。如果是这样,请用moment等进行转换。