Is it possible to search against objects within an array using search filters in Vue JS?

Currently, my search filter allows users to search for a wine by name and producer location. I would like to enhance this feature to also include searching within a list of objects in an array (grapes). Is this feasible and how can it be implemented? Please see the code snippet below for reference.

HTML:

  <input type="text" v-model="search" placeholder="Search products">
  <ul>
      <li v-for="product in filteredProducts">
         <h2>{{product.name}}</h2>
        <span>{{product.location}}</span>
      </li>
  </ul>

VUE Code:

new Vue({
  el: '#app',
    data() {
        return {
            search:'',
            products: [
              { 
                name: 'The Black Sock',
                location: 'Australia',
                grapes: ['shiraz']
              },
              { 
                name: 'Goat Roti',
                location: 'France',
                grapes: ['Shiraz' , 'Mourvedre']
              },
              { 
                name: 'Amon Ra',
                location: 'New Zealand',
                grapes: ['Chardonnay', 'Riesling']
              }
            ]
        }
    },
    computed: {
        filteredProducts:function(){
            return this.products.filter((product) => {
              return product.name.toLowerCase().match(this.search.toLowerCase()) ||  product.location.toLowerCase().match(this.search.toLowerCase());
            });
        }

        filteredSearch.sort((a, b) => {
              if (a.name< b.name)
                  return -1;
              if (a.name> b.name)
                  return 1;
              return 0;
        });
        return filteredSearch
    },
})

Answer №1

Enter any keyword you wish to search for, whether it be a name, location, or type of grapes. For example, if you type in shiraz, it will show all elements that contain shiraz in their name, location, or grapes.

let vue = new Vue({
  el: '#app',
    data() {
        return {
            search:'',
            products: [
              { 
                name: 'The Black Sock',
                location: 'Australia',
                grapes: ['shiraz']
              },
              { 
                name: 'Goat Roti',
                location: 'France',
                grapes: ['Shiraz' , 'Mourvedre']
              },
              { 
                name: 'Amon Ra',
                location: 'New Zealand',
                grapes: ['Chardonnay', 'Riesling']
              }
            ]
        }
    },
    methods: {
       sortByName(a,b){
          return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
       }
    },
    computed: {
        filteredProducts:function(){
           let comparator = this.sortByName;
           if(this.search == "") return this.products.sort(comparator);
           let search = this.search.toLowerCase();
           return this.products.filter(({name, location, grapes}) => name.toLowerCase().includes(search) || location.toLowerCase().includes(search) || grapes.find(el => el.toLowerCase().includes(search))).sort(comparator);
        }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-model="search" placeholder="Search products">
  <ul>
      <li v-for="product in filteredProducts">
         <h2>{{product.name}}</h2>
        <p>{{product.location}}</p>
        <p>{{product.grapes}}</p>
      </li>
  </ul>
</div>

Answer №2

To determine whether something exists in an array, you can utilize the includes method.

An alternative approach is to combine filter with includes, as demonstrated below:

const products = [
              { 
                name: 'The Black Sock',
                location: 'Australia',
                grapes: ['shiraz']
              },
              { 
                name: 'Goat Roti',
                location: 'France',
                grapes: ['Shiraz' , 'Mourvedre']
              },
              { 
                name: 'Amon Ra',
                location: 'New Zealand',
                grapes: ['Chardonnay', 'Riesling']
              }
            ]
            
const selectedGrapes =  'Shiraz'  

const filteredProducts = products.filter(product => product.grapes.includes(selectedGrapes))

console.log(filteredProducts)
    

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

Error in fullCalendar where events are appearing on incorrect days in the month view of the current month

https://i.sstatic.net/v8Faj.png My fullcalendar plug-in is causing some trouble. I'm trying to show events in the monthview of the calendar, but when I'm in the current month, events on the same day of the week are not displaying correctly. They ...

Counting down with JSP, AJAX, and MYSQL: A

Looking to create a unique webpage where customers who purchase a 2-hour subscription package will have the page visible for exactly 2 hours, with a countdown timer synced with a MySQL database. How can this be accomplished using JSP and servlets? What i ...

Is it possible for me to ensure that the argument passed to `res.write` is sent as one solid chunk?

When utilizing express' res.write method to send chunks back to the requestor, it is important to note that one call to res.write does not necessarily mean the argument passed will be received as a single chunk. This can complicate the process of pars ...

`Iframe displaying silverlight content is experiencing technical difficulties`

Within an ASPX page, there is an iframe set up like this: <iframe id="mapFrame" name="mapFrame" src="project/visioMap.htm" frameborder="0" width="100%" height="900px" runat="server" /> The content inside the project directory is Web page material e ...

What is the best way to handle multiple queries in NightmareJS?

The following JavaScript code utilizes NightmareJS to search a website for 3 posts and retrieve the username of the post uploader. var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }); var inputArray = [198,199,201]; ...

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...

What is the most effective way to extract Geolocation API co-ordinates from my nested function and store them in React state?

My goal is to retrieve a user's location once they click a button using the Geolocation API. <button onClick={this.setNewLatLong()}>"Use my location"</button>; I have successfully obtained the latitude and longitude coordinates with the ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

Unable to retrieve ajax responseText within a jquery function

Seeking assistance with a form designed for user registration. Utilizing jQuery and AJAX to validate email address availability upon blur event. Employing e.preventDefault(); in JQuery code to prevent form submission in case of errors. However, encounterin ...

Loop does not run as expected in TypeScript

Just dipping my toes into TypeScript here, so forgive me if I'm making a rookie mistake. Here's the code snippet I've got: const gCharData: any = {}; function buildChar() { const key = "Char1"; let currentChar = gCharData[k ...

jQuery must provide the complete object rather than just the data within it

What is the best way to retrieve the entire <div class="loan_officer_apply_now_link"><a href="">APPLY NOW!</a></div> At present, only the "a" element content is being returned <a href="">APPLY NOW!</a> Test Code $( ...

Tips for displaying unformatted text using HTML

Is there a way to display a string in HTML with all of its escape sequences preserved? For example: eipt No. : 1995,\nmount 935\nAdm. : 17/06/2016 INSTRUCTIONS : 1) This card is valid only for the student's name & for the period indic ...

Storing items in a pre-save hook using Mongoose

I have files that I need to generate, but these files include links, so the structure of the file looks like this: const file = { name: 'some name', content: 'some content, type: 'file type', links: [{ path: 'some ...

How to Retrieve a Unique Element from a Multidimensional Array using Knockout.js

I am currently working on extracting the 0 index of a nested array in a multidimensional array. My approach involves using a foreach binding to display states and cities within a <ul>. Here is the code I have so far: http://codepen.io/ntibbs/pen/vNM ...

Method for ensuring events in jQuery are fired in sequence

Currently, I am in the process of making multiple ajax calls from the browser to a service. However, I want to ensure that I am considerate to the server by not overwhelming it with all the requests at once. Is there a common method or practice for seque ...

Transfer information through the react-native-ble-plx module

To initiate a project involving connected devices, I must establish a Bluetooth connection among the different devices. The objective is to develop an application using React Native and then transmit data from this application to my Raspberry Pi. The Rasp ...

show.bs.modal event does not trigger within a bootstrap 4 modal that is loaded externally

I am trying to implement a feature where a common modal dialog can be loaded into any page from an external file. While the functionality works, I am facing an issue where the show.bs.modal and hide.bs.modal events are not triggered when the modal markup i ...

Blank area located at the bottom of the document

I'm having trouble designing a webpage without a scroll bar because there isn't much content to display on the page. I've tried searching for solutions and following steps to fix the issue, but I haven't had any success. If anyone can a ...

The user type is not yet loaded from Firestore when the view is rendered

I am currently in the process of developing an Ionic - Angular application that allows hospital patients to submit requests to nursing staff, who can then view the assigned requests based on the patient's room. Nurses have access to all requests, whil ...

Align Image According to Dimensions of the Browser

I'm looking for a way to dynamically position an image based on the width and height of the browser within an HTML file. I know that adjusting an image's width/height is possible through code like this: <script> ...