1

I have the array like this

myArray=[{
  id:1,
  date:2019-03-17,
  title:'name1'
},
{
  id:2,
  date:2019-04-17,
  title:'name2'
},
{
  id:3,
  date:2019-05-17,
  title:'name3'
},
]

how can I update it and get a new array like below

newArray=[
  {
    id:1,
    date:moment(2019-03-17).format('L'),
    title:'name1'
  },
  {
    id:2,
    date:moment(2019-04-17).format('L'),
    title:'name2'
  },
  {
    id:3,
    date:moment(2019-05-17).format('L'),
    title:'name3'
  },

]

the above is just my example. The real problem is I got dates from Postgres, and these dates do not have timezone. So I need to use moment to format all dates that I got from database Thanks

2 Answers 2

2

If you use node and pg, then you could do:

const pg = require("pg");


const PG_TIMESTAMP_OID = 1114;
const PG_TIMESTAMPTZ_OID = 1184;
const PG_DATESTAMP = 1082;

const parseDate = (date) => (date === null ? null : moment(date).format());

pg.types.setTypeParser(PG_TIMESTAMP_OID, parseDate);
pg.types.setTypeParser(PG_TIMESTAMPTZ_OID, parseDate);
pg.types.setTypeParser(PG_DATESTAMP, parseDate);

This way you'd always get the moment format when querying postgres.

If you do not use it, or don't want to, then you could just map your array:

const newArray = myArray.map(item => ({
  ...item,
  date: moment(item.date).format("L")
}));
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a foor loop and edit your object as follows,

for(var i = 0; i < myArray.length; i++) {
    myArray[i].date = "moment(" + myArray[i].date + ").format('L')";
}

1 Comment

Hi thanks, it works when I do this for(var i = 0; i < myArray.length; i++) { myArray[i].date = moment( myArray[i].date ).format('L'); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.