Search for elements in a separate array using Vue's filtering function

I have two arrays that I receive data from the backend. One contains city information and the other contains delivery times.

First:

cityArray: {
 type: Array,
 default: () => []
},

Second:

deliveryTimeArray:  {
 type: Array,
 default: () => []
}

The data comes in a regular array format, with key-value pairs. For example,

CityArray: [{"name": "Boston"}, {"name":"Detroit"}, {""}];
and DeliveryTimeArray:
[{"name": "Detroit","delivery_time: "2-7""},{"name": "Boston","delivery_time": "1-3"},{"}]
) If the city names match, I need to display the corresponding delivery time.

I attempted the following:

<div v-for='(city, index) in deliveryTimeArray' :key='index' > 
  <span :class='{ "city": findDeliveryTime(city) }'> {{ city }} </span>
</div>
///////////////
findDeliveryTime(city) {
  return this.cityArray.includes(city);
}

This code successfully finds matching cities, but I am unsure how to reference the delivery_time

Answer №1

Each of the elements in the array contains the region name within the name property. Therefore, the function findTime() must extract this property from both this.region[] and from reg (i.e., the element in the deliveryTime[] array).

Utilize Array.prototype.some() to compare each region's name with the delivery time's region:

export default {
  methods: {
    findTime(reg) {
      return this.region.some(r => r.name === reg.name)
    }
  }
}

To conditionally show the item, incorporate v-if into your template:

<span v-if="findTime(reg)">{{ reg.name }}</span>

demo 1

Alternatively, another approach to tackle the issue is to calculate the filtered results:

<template>
  <div v-for='(reg, index) in computedDeliveryTime'>
    <span> {{ reg.name }} </span>
  </div>
</template>

<script>
export default {
  computed: {
    computedDeliveryTime() {
      return this.deliveryTime.filter(d => {
        return this.region.some(r => r.name === d.name)
      })
    }
  }
}
</script>

demo 2

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

An issue arose when executing a script in elastic search, resulting in a gateway timeout error

Encountered a 504 Gateway timeout error while executing a script in elastic search. { "query": { "bool": { "filter": { "script": { "script": " doc['creted_date'].date.getMonthOfYear() == 12 " ...

"Exploring the concept of master pages in web development with the combination

Recently, I have been developing a website that functions similarly to olx, displaying ads based on the visitor's location (for example, showing Mumbai ads if the visitor is from Mumbai). Initially, I was planning to create separate pages for each cit ...

unable to display preview images using the youtubev3 API

Currently in the process of creating a YouTube clone using the YouTube V3 API import React from 'react' import { Link } from 'react-router-dom'; import { Typography, Card, CardContent, CardMedia } from '@mui/material'; import{ ...

Updating the background color of several tags with jQuery

<rect class="day" fill="#fbedf0" data-count="0"></rect> <rect class="day" fill="#cqe45b" data-count="0"></rect> I am attempting to modify the fill color values of multiple rect tags using jQuery. While I can successfully loop thro ...

How to isolate a function in React when mapping data

I am currently working on mapping data as a repeater in my React project. However, I am facing an issue with isolating the opening function, specifically with an accordion component. As I continue to learn React, I want to ensure that each accordion operat ...

What is the timing for the execution of top-level non-export code in TypeScript?

I am currently puzzled about the execution of code in files. Let's say we have a file1.ts with the following content: export interface myInterface {} export function myFunction() {} export const myConst: {} // ... and more exports // top-level non- ...

How can you tackle this issue without relying on 'arguments' and instead using the rest parameter syntax?

My instructor mentioned that I can resolve this issue without utilizing arguments in const args, but through the use of ...rest I'm not very comfortable with this operator so I could use some guidance on it. Please incorporate rest and provide types t ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

Is there a way to transfer a JavaScript variable created by an API to a PHP variable within a form submission?

I have some variables that are being generated by a JavaScript script and I am looking for the most effective way to pass them back to the PHP program that initiated the script. Since there are several variables (4-5), I prefer not to pass them through the ...

Understanding the expiration date of a product

I'm seeking assistance with identifying expiration dates from a list of data. For instance, if I have a list containing various dates and there is an expireDate: 2019/11/20, how can I highlight that date when it is 7 days away? Here's an example ...

The submission of FormData to the PHP server is causing an issue

I am having an issue with sending the formData to my PHP script using AJAX. Despite inspecting the elements, I can't find any errors in the process. Below is the structure of my form: The input values are sent to a JS file onclick event. <form c ...

How to monitor and respond to HTML modifications in a child component from a parent component in Angular framework

In the setup I have, there is a main component known as @Component({ selector: 'parent-comp' template: '<child-comp [inputData]="responseData"></child-comp> }) export class ChildComponent { public responseData: any; ...

Raycast in Three.js is struggling to locate object

Whenever I select a 3D model, my goal is to retrieve the object's ID, name, or the actual object itself in order to effectively delete it. function onDocumentMouseDown( event ) { if (enableRaycasting){ event.preventDefault(); mouse.set( ( event.c ...

Unexpected JSON data submission

I am encountering an issue with JSON. Since I am not proficient in JSON, identifying the problem is challenging. Here is the JSP code snippet. $(document).ready( function(){ window.onload = dept_select; $("#sales_dept_id").change ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

How to confirm the parent state in Angular's UI router?

In summary, I am seeking a function similar to state.is() that can verify a state with multiple child states from one of those child states? This is the structure I have: Parent 1 Child 1.1 Child 1.2 Child 1.3 Parent 2 Child 2.1 ...

delete the final directory from a file directory

let currentLocation = window.location.pathname; let directory = currentLocation.substring(0, currentLocation.lastIndexOf('/')); The current location is: /examples/html/home/ The directory is: /examples/html/home I am trying to remove the las ...

What is the best way to refresh updated .js files directly from the browser console?

Is it possible to use RequireJS 2 to dynamically reload a recently updated .js file? Let me explain my scenario: I have a Backbone.js object named Foo with a function called Bar that currently displays an alert with "abc" when called; In my webpage, I ex ...

Unable to connect Dropzone to dynamically loaded DIV using AJAX

Using Dropzone for client-side image uploads has been a breeze. Take a look at this basic example that is currently up and running: If you examine the source code, you'll notice that I am utilizing JQuery to connect Dropzone to the upload1 div ID. H ...

Is an audio player/playlist necessary for showcasing a mix engineer's skills in their

As a newcomer to the world of web development with some background knowledge from school, I work as a mix engineer and have created a portfolio website. Previously, I utilized Soundcloud and Spotify's API to showcase my mixes/songs, but the external J ...