Implementing a search filter in Vue.js using a nested for loop

I am currently working with a JSON object that contains nested objects and I need to iterate over them to extract data. Everything is functioning correctly, but now I want to implement a search/filter feature where the search is performed on the second level of the nested for loop. I have made some progress with it, but I am not receiving any data in return. Here is an example:

Link to Example

In the HelloWorld component, you will see where the search/filter functionality is being applied. However, it seems to stop outputting data after passing through the searchFilter method.

To disable the search/filter and get everything to display again, modify line #6 as follows:

from:

<div class="contentSingle" v-for="(c, i) in searchFilter" :key="i">

to:

<div class="contentSingle" v-for="(c, i) in cont" :key="i">

If anyone has suggestions on what can be done to resolve this issue, please let me know. My goal is to filter by the elements within each content inside the main data object. The data object can be found within the FauxData/dataContent.js directory.

Thank you!

-S

Answer №1

It is recommended to utilize methods instead of computed properties:

  methods: {
    filterContent(content) {
      return content.filter(item => {
        let itemUpper = item.content.toUpperCase();
        let searchUpper = this.search.toUpperCase();
        return itemUpper.indexOf(searchUpper) > -1;
      });
    }
  }

Incorporate the following code snippet in your HTML structure:

  <section id="content">
    <input type="text" id="search" name="search" v-model="search" placeholder="Search Content...">
    <div v-for="(cont, index) in content" :key="index" class="contentWrapper">
      <h1>{{ index }}</h1>
      <div class="contentSingle" v-for="(c, i) in filterContent(cont)" :key="i">
        <h3>{{ c.title }}</h3>
        <div v-html="c.content"></div>
      </div>
    </div>
  </section>

Update Applied

If you wish to hide the empty section, consider using a computed value:

  computed: {
    filteredData() {
      return Object.keys(this.content).reduce((a, cKey) => {
        const data = this.filterContent(this.content[cKey]);
        if (data.length) {
          a[cKey] = data;
        }
        return a;
      }, {});
    }
  },
  methods: {
    filterContent(content) {
      return content.filter(item => {
        let itemUpper = item.content.toUpperCase();
        let searchUpper = this.search.toUpperCase();
        return itemUpper.indexOf(searchUpper) > -1;
      });
    }
  }

Implement filteredData in the outer v-for loop

  <section id="content">
    <input type="text" id="search" name="search" v-model="search" placeholder="Search Content...">
    <div v-for="(cont, index) in filteredData" :key="index" class="contentWrapper">
      <h1>{{ index }}</h1>
      <div class="contentSingle" v-for="(c, i) in cont" :key="i">
        <h3>{{ c.title }}</h3>
        <div v-html="c.content"></div>
      </div>
    </div>
  </section>

See demonstration on codepen

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

Using jQuery to remove the last two characters from a specified class

I have a simple task at hand. I am trying to use the slice method in JavaScript to remove the last two characters from a string that is generated dynamically within a shopping cart. Instead of displaying a product as $28.00, I want it to display as $28. S ...

Webpack is unable to locate a specific custom JavaScript file

Currently, we are in the process of transitioning from grunt to webpack for our project. Within our project, we have a JS file named boiler that is used to define the core classes which are frequently accessed. __boiler__.js define(function (require) { ...

Exploring Touch Interactions in Vue.js 2.0

Recently I started working with Vue 2.0 and encountered the need to incorporate swipe gestures into my project. After exploring the official plugin called vue-touch, I discovered that it does not currently support Vue 2.0. Can anyone recommend alternative ...

JavaScript function not being executed after AJAX response in HTML

There seems to be a problem with my jQuery code. After receiving an html response from an ajax call and prepending it to a div, a div within that received html is not triggering a function in my external javascript file. In the index.php file, I have incl ...

Accessing images from subreddit using reddit API

Seeking inspiration from reddit API, I am interested in extracting images from a specific subreddit (http://www.reddit.com/r/VillagePorn) and showcasing them on a webpage. I have observed similar functionality on other websites (specifically, imgur.com/r/* ...

Is there an issue with retrieving JSON data in Swift 4?

Having an issue with parsing a weather forecast JSON using the new Swift 4 method for serializing JSON with structure. Whenever I try to print the JSON, I get the following error message: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...

Setting up initial values for React properties

Below is the React code snippet I am currently working with: this.state = { colsHiddenStatus: new Map([['rowNumber',true], ['id', false], ['firstName', false], ['lastName', false], ['mobile', false], [&a ...

Can you explain the significance of @id and @type within a json-ld context?

Can you explain the meaning of this statement in a JSON-LD context? { "@context": { "@version": 1.1, "id": "@id", "type": "@type" } } Additionally, { "@context" ...

Is it possible to activate the :active pseudoclass by pressing the 'enter' key on the keyboard using solely CSS?

The CSS: a:focus { opacity: .75 } a:active { transform: translateY(4px) } The purpose: When keyboard users tab to the link, the :focus style serves as a visual indicator Upon pressing the enter key to activate the link, the :active style provides ...

Unable to display the attributes of an object using console.log

I am attempting to log the properties of an object in TypeScript, but I am encountering issues. setTitleAndBody(result: { title: String; body: String; }) { console.log(result) console.log(result.title) } What's interesting is that if I only l ...

I'm stumped by this code; I can't figure out what's going wrong

$(document).ready(function() { $.ajax({ type: 'GET', url: 'data.json', dataType: 'json', success: jsonParser }); }); $(".btn_val1").click(function() { ...

Javascript: Uncaught TypeError - Unable to assign value to non-existent property

I am having an issue with assigning a value to a textbox, and I keep getting this error. Here is my code: This is the textbox in question: <input id="Text1" type="text" runat="server"/> Here is the dropdown list used in the function: <select i ...

I am looking to create a password generator that saves all generated options to a file

I am looking to create a custom password generator that writes all generated options to a file. For example, using the numbers "0123456789" and having a password length of 3 characters. However, I am facing an issue with the file writing process where it ...

Are there any significant advantages other than SEO for CSR + SSR web applications like nuxtjs and nextjs?

Is the main advantage of implementing SSR + CSR for SEO purposes? When you consider it, SSR actually slows down the initial load time because you have to wait for the server to render and respond with the HTML + JS, requiring a nodejs server with complex c ...

Gulp is showing an error of "Module Not Found" despite the module being present in the project

I've come across an unexpected issue and I'm at a loss for solutions. As part of my exploration into JS unit testing, I am configuring gulp with Jasmine. However, when I run my gulp build, I encounter the following error: Error: Cannot find modu ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Please provide values in the input box, with each value separated by

I attempted the following code: success: function (result) { for (var i = 0; i < result.d.length; i++) { var emails = new Array(); emails = result.d[i].Emailid; alert(emails); $("#EmailCC").val(emails); ...

Is there a way to prevent the window.on('beforeUnload') event from triggering when using the <a> tag?

For my project, I require a user confirmation alert to appear when the user attempts to close the window or tab using the X button. However, the window.on('beforeUnload') function also triggers for hyperlinks. How can I prevent the leave page al ...