Using Vue to conditionally add values to an array

In my Vue website, I have a function that makes a call and gets an object with a date in the response.data:

Here is an example of an object in response.data:

response.data = {available_at: '2019-08-12', title: 'Test'}

Currently, I am fetching this data and creating an array called dates using this.dates, which is working fine. But, I want to check if the value of response.data.available_at is equal to the current date. If it matches, then add it to this.dates; otherwise, add it to this.pastDates.

Is there a way to modify my code to achieve this?

fetch() {
    axios.get('/items/')
    .then(response => {
      // handle success
      console.log(response.data)
      this.dates = response.data
    })
    .finally(function() {})
}

UPDATE: The structure of response.data (a list of objects)

(51) [{…}, {…}, {…}, {…},...]
0:
available_at: "2019-09-16"
title: "2"

Answer №1

Can we consider the date as a string in this scenario? If so, you may want to try implementing something similar to the following code snippet:

if (response.data.available_at === new Date().toISOString().slice(0, 10)) {
//add the item to this.dates
} else {
// add the item to this.pastDates
}

Considering that response.data is an array of objects, the logic can be structured as shown below:

response.data.forEach(item => {
    if (item.available_at === new Date().toISOString().slice(0, 10)) {
        this.dates.push(item);
    } else {
        this.pastDates.push(item);
    }
});

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

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

Error with jQuery variables

I'm encountering an issue with my code. The input box I have should display the value of a button when clicked. What I want is for the currently displayed value in the input box to be saved in a variable when a button is pressed, and then update to s ...

The impact of using 'new Function' on performance

When I utilize AJAX to load a script file and run its content, my approach involves the following: new Function('someargument',xhr.responseText)(somevalue); However, MDN states the following: Function objects created with the Function constr ...

Can you explain the distinction between firstChild and childNodes[1]?

Exploring the distinction between child nodes and child elements within JavaScript DOM: For instance, var myTbodyElement = myTableElement.firstChild; versus var mySecondTrElement = myTbodyElement.childNodes[1]; Is it possible to interchangeably use firs ...

Transferring information to the server using a fetch request

Can anyone help me understand why the server is returning POST {} {} as empty objects after sending a request? I'm confused about where this data has gone. Why did it disappear? I'm completely lost on how to solve this... index.js: window.add ...

Steps for eliminating curly braces and renaming the key-value pairs in a JSON object

I have a JSON output that looks like this: { "intent": "P&P_Purchase", "value1": { "date1": "30-Dec-19", "prd_desc": "NEEM UREA OMIFCO (45 KG)", "qty": &quo ...

What is the best way to create a new browser window for a pop-up?

Using the following JavaScript code will open a popup: window.open('http://www.google.com','mywindow','width=400,height=200'); If you call it two times like this: window.open('http://www.google.com','mywindow ...

The phenomenon of lithophane in Three.js

Is there a way to achieve the Lithophane effect using three.js? . I've experimented with different materials featuring transparency and opacity, but haven't been successful. <html lang="en"> <head> <title>Lith (Three. ...

Why does Vue continuously insert undefined values when adding non-consecutive indexes to an array?

In my application, users can select values from a dropdown list and add them to an array by clicking the "add" button. The goal is to use the selected value's id as the index in the array. For example: List of Values 1 - Apple 3 - Bananas 8 - P ...

Utilizing 'nestjs/jwt' for generating tokens with a unique secret tailored to each individual user

I'm currently in the process of generating a user token based on the user's secret during login. However, instead of utilizing a secret from the environment variables, my goal is to use a secret that is associated with a user object stored within ...

Keeping a specific value in a dropdown selection with the help of AngularJS

Is it possible to have a pre-selected {{k.toTime}} initially displayed in the select input? I am having trouble viewing the values of {{k.toTime}} or {{k.fromTime}} as originally set in the select input. The myFormat filter is used to convert minutes int ...

React displays the previous state

Can someone assist me with the code provided below? import React, { useState, useEffect } from 'react'; import { Container, Row, Col, ListGroup, Button, InputGroup, FormControl } from 'react-bootstrap'; import FileUpload from './C ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

Utilize Require.js to Load Dropzone.js Library

I am interested in integrating Dropzone.js into an application that is built using Backbone and Require.JS. However, I am unsure of the correct implementation process. Should I utilize require()? What is the most effective way to handle this integration? ...

Mastering the art of simultaneously running multiple animations

Utilizing two functions to apply a Fade In/Fade Out effect on an element. Confident in the functionality of both functions, as testing them sequentially in the Console proves their effectiveness. However, executing: fadeIn() fadeOut() seems to result in ...

The Store Variable in Nuxt 3 is not being updated

Struggling to get my store functioning properly. I'm familiar with creating a store using vue 3, but with Nuxt 3, my values don't update as expected. Here's my function for adding something to the store: <script setup> function addW ...

Adjust the line spacing in CSS depending on the length of the text

Upon page load, a ul list is dynamically generated via JavaScript. The relevant code snippet is as follows: <ul class="tweet_list"><li class="tweet_first tweet_odd"></li></ul> Related CSS: ​ul.tweet_list li { height: 55px; ...

Where can I locate htmlWebpackPlugin.options.title in a Vue CLI 3 project or how can I configure it?

After creating my webpage using vue cli 3, I decided to add a title. Upon examining the public/index.html file, I discovered the code snippet <title><%= htmlWebpackPlugin.options.title %></title>. Can you guide me on how to change and cu ...

Is it possible to dynamically update the contents of a modal body and modal footer using

I'm dealing with a modal that dynamically populates two sections: modal-body and modal-footer. However, the issue is that only the content of modal-body changes dynamically while modal-footer remains static. Here's an example of the HTML code (w ...

Autocomplete feature seems to be functioning properly in the online demonstration, while it does not seem

I can see that the autocomplete feature is working in the example provided, but it's not functioning properly in my attempt. What could be causing this issue? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> & ...