Retrieving a date and time value from an object based on a specific range

Having trouble displaying all the user IDs and creation dates within a specific date range in a table. I'm struggling with filtering the data based on dates. Can someone help me identify what I might be doing wrong? I've attempted to replicate the API response in the data state, then filter that data to retrieve information from a certain date range. The console statement doesn't seem to work inside the getDateData method in this code sandbox demo

<template>
  <div @click="getDateData">Hello</div>
</template>

<script>
export default {
  data() {
    return {
      newData: {},
      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-04-14T12:24:27.577Z";
      const toDate = "2021-04-14T14:17:13.127Z";
      this.newData = this.usersFromDb.forEach((item) => {
        console.log(item.users_by_id.users.created_at);
        return (
          item.date.getTime() >= fromDate.getTime() &&
          item.date.getTime() <= toDate.getTime()
        );
      });
    },
  },
};
</script>

Answer №1

To properly iterate over the object (usersFromDb), it is recommended to use .filter or .map instead of forEach on the array.


UPDATE: Below is the corrected and functional code snippet.

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

<script>
export default {
  data() {
    return {
      newData: [], // Must 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' // Example values
      const toDate = '2021-06-14T14:17:13.127Z' // Updated values for comparison
      this.newData = this.usersFromDb.data.users_by_id.users.filter((user) => {
        console.log('user', user) // Improved naming
        return (
          new Date(user.created_at).getTime() >= new Date(fromDate).getTime() &&
          new Date(user.created_at).getTime() <= new Date(toDate).getTime()
        )
      })
    },
  },
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty interpreting JSON Object, converting to a string, or accessing JavaScript property

My current challenge involves utilizing a Firefox addon that supplies me with the following variable: [{errorMessage:"TypeError: a is null", sourceName:"http://pagead2.googlesyndication.com/pagead/js/graphics.js", lineNumber:17, console:null}] From Fire ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

Pattern matching for a string with numerous repetitions using Regular Expressions

There's a [tree] and a cat and a [dog] and a [car] too. I am looking to find the words inside each set of square brackets. The resulting array will be tree, dog, car My attempt at using match(/\[(.*)\]/g) didn't work as expected. It ...

Invalid Operation: The value 'undefined' cannot be used as a function

I've been working on implementing a date picker feature for an HTML form. In the HTML header, I have included the following script: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> The script I&apo ...

What is the process for choosing every child (regardless of level) of a parent using jQuery?

Is there a way to unbind all elements from a parent node using jQuery? How can I effectively select all children, regardless of their nesting level, from a parent node? I attempted the following: $('#google_translate_element *').unbind('c ...

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

Populate the Vue.js2 canvas graph with dynamically assigned array values

I am attempting to fill a canvas graph with random array values. Utilizing the Vuejs2 library, I have implemented the template for displaying the graph data as shown in the code below: import {Line} from 'vue-chartjs' export default Line.extend ...

Using ReactJS: Injecting components and passing variables in extended components without the need for functions

Currently, I am utilizing apollo for the authentication process in my nextJS application. My next task is to incorporate i18n support, but I am encountering some fundamental issues: The primary obstacle lies in handling class Index extends React.Component ...

Ways to update the background shade of tr td elements inside a table

I'm having trouble changing the background color of td elements within my table. The browser keeps giving me an error message that says "Cannot read property 'children' of undefined". Despite this, my JavaScript can still navigate through al ...

Creating a clickable link that dynamically updates based on the span and id values, and opens in a new browser tab

I am attempting to create a clickable URL that opens in a new window. The URL is being displayed and updated on my HTML page in the following manner: Python Code: def data_cb(): return jsonify(waiting=await_take_pic()) Javascript Code: jQuery(d ...

How to turn off and on all elements within a Div tag

Is there a way to disable all elements within a Div tag? I've managed to disable input types successfully, but I'm struggling with links. I attempted the solution provided here, but it didn't work. Here's the code snippet that worked f ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...

What type of response does XHR provide when there is no connection available?

Imagine I launched Google Chrome and its corresponding extension. The extension relies on the XmlHttpRequest object for functionality. However, upon starting the browser, I realized there is no internet connection available. In this scenario, what will t ...

Failure to Reach AngularJS ng-click Function

When trying to add a new product to the product list, I am facing an issue. The products load correctly but the ng-click function is not being triggered. (The alert I set up in the addProduct function is not appearing). HTML <div ng-controller="Produc ...

Chrome will automatically retry an AJAX POST request if it times out after 10 seconds

I am in the process of creating a React JavaScript application using a back end powered by Node.js and Express. The software versions being used are as follows: React: ^16.0.0 Node: v8.0.0 Express: ^4.14.0 Chrome: Version 63.0.3239.84 (Official Build) (64 ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

Using Promise.all within the useEffect hook in ReactJS

I encountered a scenario where I needed to make two API calls one after another, with the second call dependent on the response from the first one. Fortunately, I managed to utilize the Promise.all function along with axios in my React project. However, I ...

Exploring the process of incorporating types for a Vue plugin

I am currently trying to integrate a self-made plugin for Vue with TypeScript. However, when I try to use the method from my vue prototype, I encounter an issue where my method $auth is not recognized on type 'myComponent'. I have also included ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...