Nest multiple v-for loops within each other to create a

<div>
    <q-card              
        v-for="box in boxes"
        :key="box.id">
        <q-item>
            <q-item-section>
                <span> {{ box.name }} </span>
            </q-item-section>
        </q-item>

        <q-list>
            <q-item
                v-for="tool in box.tools"
                :key="tool.id"
                clickable
            </q-item>
           <q-item-section>
               <span> {{ tool.name }} </span>
           </q-item-section>
            
        </q-list>
    </q-card>
</div>

Form input filter value

inputFilterValue = "box A"

Filter boxes

Edited with return.

computed: {
    boxes(){
      return boxes.filter(box => {
            return box.name.toLowerCase().match(inputFilterValue.toLowerCase())
        });
    }
}

This solution is effective

Is there a way to apply the same filtering logic to nested v-for loop on box-tools list?

UPDATE:

CODEPEN: https://codepen.io/ijose/pen/NWyoRMX

Answer №1

To filter elements in an array using JavaScript, you can utilize the filter() method combined with the some() method. The some() method examines whether any element meets a specified condition.

Check out this demonstration:

new Vue({
  el: '#app',
  data: {
    value: null,
    boxes: [],
    dataObj: [{
      id: 1,
      name: 'Box A',
      tools: [{
        id: 1,
        name: 'Tool A'
      }, {
        id: 2,
        name: 'Tool D2'
      }]
    }, {
      id: 2,
      name: 'Box B',
      tools: [{
        id: 1,
        name: 'Tool B'
      }]
    }, {
      id: 3,
      name: 'Box C',
      tools: [{
        id: 1,
        name: 'Tool C'
      }]
    }]
  },
  mounted() {
    this.boxes = structuredClone(this.dataObj);
  },
  methods: {
    inputFilterValue(filterField) {
      if (filterField === 'box') {
        this.boxes = this.dataObj.filter(box => box.name.toLowerCase().match(this.value.toLowerCase()))
      } else {
        const filteredToolsArr = this.dataObj.map(box => {
          const filteredTool = box.tools.filter(({ name }) => name.toLowerCase().match(this.value.toLowerCase()));
          return { ...box, tools: filteredTool }
        })
        this.boxes = filteredToolsArr.filter(obj => obj.tools.length);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  Filter : <input type="text" v-model="value" @keyup="inputFilterValue('tool')"/>
  <ul v-for="box in boxes" :key="box.id">
    <li>{{ box.name }}</li>
    <ul v-for="tool in box.tools" :key="tool.id">
      <li>{{ tool.name }}</li>
    </ul>
  </ul>
</div>

Answer №2

Ensure that in the filter callback for boxes, there is a condition checking if the tool name matches the provided inputFilterValue

computed: {
    boxes(){
        return boxes.filter(box => {
          return box.name.toLowerCase().match(inputFilterValue.toLowerCase()) ||
            box.tools.filter(tool=>tool.name.toLowerCase().match(inputFilterValue.toLowerCase())
        });
    }
}

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

Typescript code encountering unexpected behavior with Array.includes()

Below is a snippet of TypeScript code from my NextJS application: const holeSet:any[] = []; ..... let xx = 1, yy = 2; holeSet.push({x:xx,y:yy}); xx = 3; yy = 4; holeSet.push({x:xx,y:yy}); holeSet.map((e) => { console.log("element ::"+JSON ...

Using Nested ng-repeat for Values and Keys in Angular

Struggling with implementing nested ng-repeats in my code. I have a JSON object with multiple layers and attempting to iterate through them to display the data. Here is the structure of the JSON: { "status": "success", "data": { "Mat": { "tota ...

Discovering the art of incorporating various color palettes within a single stylesheet using HTML

I'm curious about incorporating multiple color schemes into a single stylesheet that can be activated by clicking, similar to the functionality found in platforms like WordPress and Magento. These platforms offer themes with various color options avai ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Tips for sharing content within an iframe

Despite my efforts to find a solution, I have been unable to come across one that aligns with my specific situation. I currently have a form for inputting person data. Within this form, there is an iframe containing another form for adding relatives' ...

Problem with applying Jquery Datatable in conjunction with Bootstrap 4 modal

My current setup involves a datatable that looks like this: Whenever a user clicks on the number of items, it opens a Bootstrap 4 modal like this: However, I am facing an issue with the search and pagination functionality when the datatable is within the ...

Is there a way to use jQuery to centrally align the accordion item that I have chosen?

My attempts to use `this.scrollIntoView({behavior: "smooth"}) were yielding inconsistent results in terms of where the selected item would land on the page. I believe I might need to utilize scrollTop(), but as someone who is new to jQuery, I am ...

I am looking to create distinct alphabetical keys in sequential order using AngularJS

Is there a way to create keys in alphabetical order that start with aaaaa and continue on to aaaab, aaaac, and so forth, properly generating the keys? This is how I would like my JSON sample to be created: var keygen={aaaaa, aaaab, ...

Utilizing Google Maps to generate outcomes for an online platform

My approach with Google Maps is a bit unconventional. Instead of rendering images, I aim to execute JavaScript code that processes data and returns a text response. However, I soon realized that running JavaScript as a remote web service might not be pos ...

Reviewing the element names in a jQuery-selected array of objects

I'm new to javascript and the jquery library and I need to work with an array of input fields that have specific names for validation. Each input field is named NS[0], NS[1], etc., and the total number of these fields is generated dynamically in the c ...

The PHP script retrieves the entire content of the file

Currently in the process of learning PHP, I am experimenting with connecting PHP and JavaScript using AJAX calls. Here is how my JavaScript file is set up: $.ajax({ type:"GET", url:"test.php", success:function(data) { console.log(data) ...

Using the OR operator in an Angular filter

How can I create a filter with a range slider that shows multiple categories when it's in a certain position? I have tried using the code below to filter based on the range, but it only captures the first word after the OR operator. Can anyone provid ...

Issues with Google charts loading may arise on ajax calls

Recently, I have been experimenting with incorporating Google Charts into my website to showcase data from Google Analytics. To enhance user experience, I decided to split my analytics reports into distinct sections such as Pages, Browsers, Operating Syst ...

Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it. Here's the current code snippet: <div class="position-sticky bottom-0" ...

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...

What is the most efficient method for completely updating every field in a MongoDB document?

If I need to update an entire document and overwrite all fields except for _id, which of the three methods is the most efficient in terms of resource consumption: 1. Setting the complete document as the update parameter, passing all fields Example: coll ...

The functionality of opening a new tab when clicking on a link image is not functioning correctly on Mozilla, whereas it

Check out my code below: <a target="_blank" href="#" onclick="window.open('https://www.google.com','_blank');"> <img src="#{request.contextPath}/resources/img/landing-page/terdaftar-kominfo.png" /> </a> ...

Combining Static and Dynamic Elements in Vuejs Templates: Best Practices

Here's my VueJS template: template: ` <div> <div>{{ date}}</div> <div>{{ title }}</div> <div>username: <a href='#profile?user={{ username }}'>{{ username }}</a></div> < ...

struggles with integrating arrays into object attributes in JavaScript

When working with object attributes, keep in mind that they only hold the first element of the assigned value let groupedDepActivities=[] groupedDepActivities.push({ id:1, term_activity:{ terms:[{id:1},{from:'her ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...