[Vuejs]-Returning datetime value from an object depending of a range

3👍

You cannot loop on an object (usersFromDb) with a forEach and in this case, you should prefer a .filter (or a .map) to loop on the given array.


EDIT: alright, here is the whole fixed and working code.

<template>
  <div>
    <button @click="getDateData">get the data</button>
    <div v-for="date in newData" :key="date.id">{{ date.id }}</div> <!-- clean display of all the ids of the data -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      newData: [], // ! needs to be an array
      usersFromDb: {
        data: {
          users_by_id: {
            users: [
              {
                id: '123',
                created_at: '2021-04-14T12:24:27.577Z',
              },
              {
                id: '456',
                created_at: '2021-04-14T12:24:27.577Z',
              },
            ],
          },
        },
      },
    }
  },

  methods: {
    getDateData() {
      const fromDate = '2021-02-14T12:24:27.577Z' // I modified those for example purposes
      const toDate = '2021-06-14T14:17:13.127Z' // same, otherwise it's pretty useless to make a comparison if they are equal
      this.newData = this.usersFromDb.data.users_by_id.users.filter((user) => {
        console.log('user', user) // better namming
        return (
          new Date(user.created_at).getTime() >= new Date(fromDate).getTime() &&
          new Date(user.created_at).getTime() <= new Date(toDate).getTime()
        )
      })
    },
  },
}
</script>
👤kissu

Leave a comment