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

Enhancing the model using Sequelize JS

Currently, I am in the process of developing a basic API using Express and Sequelize JS. Recently, I encountered an issue while attempting to update a record with req.School, but no changes seemed to occur. Despite checking the code below thoroughly, I did ...

Creating subpages using IDs can be accomplished by following these simple steps

Currently, I am in the process of developing a website that contains a plethora of information, specifically news articles. Each news article on my site features an introduction and a header. Upon clicking on a particular news article, the full content is ...

A helpful guide on how to dynamically input database values into the href attribute of an 'a' tag

How do I successfully pass an ID to href in my code? When I try to return it via req.params, it keeps coming back as undefined. I need the ID from the URL in order to use the findOne method to access the data stored in the database. I've searched thr ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

Tips for including subjects in JSON data

I am trying to include the subject in JSON data so that I can fetch it using $.each(data.subject). Below is my API code where I am retrieving all the data encoded in JSON format. Any assistance would be greatly appreciated. [{"id":"79","FirstName":"Elon", ...

PHP's 'include' function is now being ported into modern Javascript as a new method

As the library of JS frameworks continues to expand, I'm wondering if there is a simple JS replacement or alternative for PHP's 'include' function. Is PHP include still a relevant method for including chunks of code, or are there better ...

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

The POST function in jQuery often returns the [Object object] result

Looking to extract a string from a PHP file using jQuery's post method. function getString(string) { return $.ajax({ type: 'POST', url: 'scripts/getstring.php', data: { 'string': string } ...

Is there an alternative to the jQuery :contains selector?

How can I choose an option from a drop-down menu based on its text value? When I execute the following code: var desiredText = "Large"; $("#size option:contains(" + desiredText + ")").attr('selected', 'selected'); it ends up selecting ...

What is the best way to extract data from a JavaScript object received from multer?

Currently, I am facing an issue while trying to utilize multer for handling the upload of a CSV file in Express. The goal is to parse the uploaded file line by line. Although I can successfully retrieve the file as an object stored in req.body, I encounter ...

When invoking the jQuery ".load('pageName')" method, HTML pages are not loaded from the application cache

I have been working on incorporating the html5 offline caching functionality into our html pages, and everything seems to be running smoothly with jQuery version 1.4. However, I encountered a problem when I upgraded to jQuery 1.8. Specifically, issues aro ...

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...

Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to impro ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...

Designing an architecture for a Java, Android, and database application - what will the final app's appearance be

I am currently working on a website where users need to complete tasks using an Android device: Fill out a simple HTML document. Sign the document on their Android device. Save the data entered into a database on the website. Some key points to consider ...

Utilize the $scope variable as a JSON object for interacting with the $http service

Is there a way to extract all the data from Angular's scope service without creating an additional object? I am trying to send everything on the scope to a server using $http.post, but it seems that $scope is a circular structure, resulting in "Conver ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Deploying an Angular application created using Yeoman to Heroku

I have been following some instructions on how to deploy my project, such as this guide or this tutorial. However, I am unable to get it to work properly. This is the code in my server.js file: var app, express, gzippo, morgan; gzippo = require('gz ...