Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering.

Dom

<v-container>
         <v-card>
            <div>
               <v-text-field label="Search" v-model="searchValue"></v-text-field>
            </div>
         </v-card>
      </v-container>
      <div v-for="items of filterfaq" :key="items.category"> 
         <h2>{{ items.category }}</h2>
         <v-expansion-panels>
            <v-expansion-panel v-for="subitems of items.content" :key="subitems.qus">
               <v-expansion-panel-header>{{ subitems.qus }} {{subitems.views}}</v-expansion-panel-header>
               <v-expansion-panel-content>
                  {{ subitems.ans }}
               </v-expansion-panel-content>
            </v-expansion-panel>
         </v-expansion-panels>
      </div>

Script

import { faq } from '../../data.js';
   export default {
      data: () => ({
         faq,
         searchValue : ''
      }),
      computed:{
         filterfaq () {
            const search = this.searchValue.toLowerCase().trim();
            if (!search) return this.faq;
            return this.faq.filter(item => {
               return item.content.filter(item => {
                  return item.qus.toLowerCase().indexOf(search) > -1
               });
            });
         }
      }
   }

Data.js

export const faq = [
    {
        id:1,
        category:'General Questions',
        content: [
            {
                subid:1,
                qus: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit?',
                ans: ' Phasellus a est id mi gravida congue.',
                views: '225'
            },
            {
                subid:2,
                qus: 'Duis porta ante ac dui iaculis, nec interdum ligula semper?',
                ans: ' Phasellus a est id mi gravida congue.',
                views: '225'
            }
        ]       
    }
 ]

The faq array has nested arrays with 'content', making it challenging to search properly. I have attempted the code above but it does not provide the desired results.

Updated: I now need to filter data from the next nested array.

export const faq = [
    {
        id:1,
        category:'General Questions',
        content: [
            {
                subid:1,
                qus: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit?',
                ans: ' Phasellus a est id mi gravida congue.',
                views: '225',
                items:[{
                    subqus: 'Lorem ipsum dolor sit amet?'
                    subans: 'Lorem ipsum dolor sit amet.'
                }]
            },
            {
                subid:2,
                qus: 'Duis porta ante ac dui iaculis, nec interdum ligula semper?',
                ans: ' Phasellus a est id mi gravida congue.',
                views: '225',
                items:[{
                    subqus: 'Lorem ipsum dolor sit amet?'
                    subans: 'Lorem ipsum dolor sit amet.'
                }]
            }
        ]       
    }
 ]

How can I achieve this?

Answer №1

If you are currently utilizing the filter faq, the process involves either selecting all the content of each item or none at all.

An alternative approach could be:

function filterfaq () {
  const keyword = this.keywordValue.toLowerCase().trim();
  if (!keyword) return this.faq;
  return this.faq.map(item => {
    return {
      ...item,
      content: item.content.filter(question => {
        return question.qus.toLowerCase().includes(keyword);
      }),
    }
  });
}

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

Is it possible to exclusively focus on the specified data attributes?

Is there a method to specifically target the 'data-season' attribute with the value "winter"? This is my HTML: <li data-season="summer">summer <ul class="groups"> <li data-item="beach">beach</li> <li data-item ...

Unable to access Vue.js cookies: they are not defined

I integrated vue-cookies into my project successfully. In the main.js file, I added the following code: createApp(App) .use(store) .use(router, axios, VueCookies) The script section in App.vue file looks like this: <script> import Navbar fr ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

Discovering the process of retrieving information from Firebase using getServerSideProps in NextJs

I've been exploring ways to retrieve data from Firebase within GetServerSideProps in NextJs Below is my db file setup: import admin from "firebase-admin"; import serviceAccount from "./serviceAccountKey.json"; if (!admin.apps.len ...

What is the best way to convert the data stored in an object to an array?

I have a function that is constantly checking for temperature data: {"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41", "g":"100", "h":"42.6"} My goal is to graph this data over time, but I'm struggling with how to structure it to fit the f ...

Using a PHP WordPress Loop, eliminate the comma following the final object in the Schema array

My Google Schema Markup for a "Product" includes a loop that displays "Reviews". Below is an excerpt of the code: "review": [ <?php $args = array( 'post_type' => 'my_reviews', & ...

"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and cont ...

Encountered an error: data.map is not functioning as expected in the React component

Hi there, I've encountered a small issue with my modal component. The error message I'm getting is: Uncaught TypeError: meatState.map is not a function. Any suggestions on what may be causing this problem? Your assistance would be greatly appreci ...

"Maximizing the potential of a single domain by hosting multiple websites with distinct paths such as domain.fr/siteA, domain.fr/siteB, and domain.fr/siteC using Docker in conjunction with

Just curious about the distinctions between import { getContent } from '@/assets/welcome-content.js' import Navigation from '@/components/Navigation' and import { getContent } from '~/assets/welcome-content.js' import Navigat ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Ways to pass information from a parent component to a child component in Vue.js

I am currently embarking on my Vue.js journey by creating an app for educational purposes. Here is what I aim to achieve: In my parent component, there are multiple buttons with distinct IDs. The child component will await these IDs from the parent and ...

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

Question about using React, NPM, Vite, Babel, and Node.js together

I want to confirm my understanding. So, if I decide to create a react 'app' and incorporate babel for jsx support. Then, I opt for vite for enhanced development runtime and packaging. Lastly, I utilize node.js to execute my code. To sum it up, ...

How can an object with a computed property be passed to a child component?

<template> child-component( v-for="item in items" :item="item" ) </template> <script> data() { return { items: [], valueFromApi: null, } }, computed: { someCompProp() { return val // math based o ...

The drag-and-drop feature requires the element to be placed in a designated slot

I encountered an issue while trying to integrate vuedraggable into my Notebook application. When I added the draggable component, I received an error message that read: "draggable element must have an item slot." The code snippet and error details are prov ...

Sending JSON object arrays from Vue.js to Laravel using AXIOS: A Step-by-Step Guide

My Laravel API endpoint needs to receive the following format in order to successfully add it to the database: { ICAO: 'ABC', name: 'The name of Airport', place: 'city', country: 'country' } I have created ...

Strategies for maintaining pristine Firebase child paths

I have a list of data that I want to structure in Firebase. However, I encountered an error: Error: Firebase.child failed: The first argument provided is not a valid path. Path names should not include ".", "#", "$", "[", or "]" characters and must be no ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

How to toggle hidden links with AngularJS or vanilla JavaScript with a click事件

When the "Show all" button is clicked, I would like to display all elements. If the "1st half" link is clicked, I want to show "abc", "def", and "ghi". When the 2nd link "2nd half" is clicked, I want to display "jkl", "mno", and "pqr". Then, when the "show ...

Fixing the issue: "Tricky situation with JavaScript not working within Bootstrap 4's div tag while JS functions properly elsewhere"

Currently, I'm working on implementing a hide/show function for comments using JavaScript. Fortunately, I was able to find a helpful solution here (thanks to "PiggyPlex" for providing the solution on How can I hide/show a div when a button is clicked? ...