I have an array of objects
const array =[{
"id": 1,
"time": "2021-09-22T05:36:22.484Z"
},
{
"id": 2,
"time": "2021-10-22T03:25:26.484Z"
}]
I want to replace all the time values after converting to a timezone.
I am able to convert to timezones using
moment.tz("time","America/Toronto").format("YYYY-MM-DD HH:mm:ss)
but not sure how to loop through to replace the time value of every object.
So ideally, I would have something like:
const array =[{
"id": 1,
"time": "2021-09-22 15:00"
},
{
"id": 2,
"time": "2021-10-22T 12:00"
}]
CodePudding user response:
Based on your data, you could simple use forEach
and manipulate the time property as per your needs.
const array =[
{ "id": 1, "time": "2021-09-22T05:36:22.484Z" },
{ "id": 2, "time": "2021-10-22T03:25:26.484Z" },
]
array.forEach(x => {
x.time = moment(x.time).utcOffset(90).format("YYYY-MM-DD HH:mm:ss")
})
CodePudding user response:
You could use map()
to loop over the array and create a new array with the updated data.
const array = [{
"id": 1,
"time": "2021-09-22T05:36:22.484Z"
}, {
"id": 2,
"time": "2021-10-22T03:25:26.484Z"
}]
const result = array.map(({id, time}) => {
return {
id,
time: moment(time).utcOffset(90).format("YYYY-MM-DD HH:mm:ss")
}
});
CodePudding user response:
array=array.map(ar=>{
ar.time= convertedtimezone
//convert ar.time into timezone and assign it to ar.time
return ar
)
CodePudding user response:
try this...
[{ "id": 1, "time": "2021-09-22 15:00" }, {"id": 2,"time": "2021-10-22T 12:00" }].map(ele=>{return {...ele,time:moment.tz(ele.time,"America/Toronto").format("YYYY-MM-DD HH:mm:ss)}})