-3

I have an array of objects, it contains some data time value. How can I find the object key with "Date" and covert the value to moment date time?

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"}
]

First I want to check if the object key has the string of "Date", then it would convert the object value to moment(value).format("YYYY-MM-DD h:mm:ss a")

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"}
]
susu watari
  • 177
  • 1
  • 2
  • 11
  • 2
    Possible duplicate of [Check if a string is a date value](https://stackoverflow.com/questions/7445328/check-if-a-string-is-a-date-value) – Hyyan Abo Fakher May 15 '19 at 17:43
  • It needs to handle the object keys – susu watari May 15 '19 at 17:44
  • Use [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) to loop through the array. Inside, use [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) to loop though each property of the object. Check if it's a date (You'll find many ways to do this part) – adiga May 15 '19 at 17:48

2 Answers2

1

All you need to do is to loop over array and then object values and update them if the key string contains Date as you suggest your condition to be which you can do by using indexOf function

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>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You can use moment.isValid to check if the date is valid (since you already are using 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>

Then you would map via map over the object keys and for each of those keys check if they point to a valid date. if so convert with moment etc.

Akrion
  • 18,117
  • 1
  • 34
  • 54