简体   繁体   中英

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:

    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

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

For what it's worth, here's the OP snippet running, improved slightly by using for-of, and (not sure if this is an improvement or a work-around) by using the native timezone offset.

 let 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" } ]; for (const obj of data) { obj.date = moment(obj.date).utcOffset('-7:00').format("YYYY-MM-DD"); } console.log(data);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM