0

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"
}]
2
  • 2
    Loops/iteration or map. Commented Sep 22, 2021 at 6:53
  • 2
    array.map(({ time, ...args }) => ({ time: moment(...), ...args })) Commented Sep 22, 2021 at 6:55

4 Answers 4

4

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")
})
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
array=array.map(ar=>{
ar.time=  convertedtimezone
//convert ar.time into timezone and assign it to ar.time
return ar
)

4 Comments

If you're modifying the original object, you should use a forEach instead of a map
okay Thanks got it, can you tell me why
'Cause it's unnecessary to create a new array here, if the change is reflected in the original array anyway.
forEach manipulates the current object. Map on the other hand returns a new object without mutating the current object iterated on.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.