gpt4 book ai didi

javascript - 如何使用javascript更新数组中对象的值

转载 作者:行者123 更新时间:2023-11-30 13:49:29 32 4
gpt4 key购买 nike

我有这样的数组

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'
},
]

我怎样才能更新它并获得如下所示的新数组

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'
},

]

以上只是我的例子。真正的问题是我从 Postgres 得到了日期,而这些日期没有时区。所以我需要使用 moment 来格式化从数据库中获取的所有日期谢谢

最佳答案

如果您使用nodepg,那么您可以:

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);

这样你在查询 postgres 时总能得到时刻格式。

如果你不使用它,或者不想使用它,那么你可以只映射你的数组:

const newArray = myArray.map(item => ({
...item,
date: moment(item.date).format("L")
}));

关于javascript - 如何使用javascript更新数组中对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58573128/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com