Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify an array of objects with for in

I’m trying to format a date inside an object.

I’m currently have the next array of objects:

    [
      { date: 2022-01-03T05:00:41.560Z },
      { date: 2022-01-03T22:54:33.980Z },
      { date: 2022-01-03T22:50:26.920Z },
      { date: 2022-01-03T22:32:29.660Z },
      { date: 2022-01-03T22:22:58.480Z }
    ]

And I’m trying to do the next:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    for (const prop in obj) {
        obj[prop].date = moment(obj[prop].date).tz("America/Vancouver").format("YYYY-MM-DD");
    }

Expecting:

    [
      { date: 2022-01-02 },
      { date: 2022-01-03 },
      { date: 2022-01-03 },
      { date: 2022-01-03 },
      { date: 2022-01-03 }
    ]

But I can’t

let obj = [
{ date: "2022-01-03T05:00:41.560Z" },
{ date: "2022-01-03T22:54:33.980Z" },
{ date: "2022-01-03T22:50:26.920Z" },
{ date: "2022-01-03T22:32:29.660Z" },
{ date: "2022-01-03T22:22:58.480Z" }
];
for (const prop in obj) {
  obj[prop].date = moment(obj[prop].date).tz("America/Vancouver").format("YYYY-MM-DD");
}
console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js" integrity="sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQuzihiBCvUEB3CVxHvsShF86wBWwQORNxNINlBPuq7rG4WWhNiTVHFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

modify it, I keep getting the original array

>Solution :

I recommend to use Array.map for this transformation:

const data = [
  { date: '2022-01-03T05:00:41.560Z' },
  { date: '2022-01-03T22:54:33.980Z' },
  { date: '2022-01-03T22:50:26.920Z' },
  { date: '2022-01-03T22:32:29.660Z' },
  { date: '2022-01-03T22:22:58.480Z' }
];

const res = data.map(
  ({ date }) => ({
    date: moment(date).tz("America/Vancouver").format("YYYY-MM-DD")
  })
);

console.log(res);

in this example we are deconstructing each object and only extracting date, and return a new object that’s only got date in it

Taking below comments into account, try Array.forEach:

data.forEach(
  ({ date }, index) => {
    data[index].date = moment(date).tz("America/Vancouver").format("YYYY-MM-DD");
  }
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading