Searching for a specific element in Vue.js using its unique identifier (ID) can be

I have a new project using Vue. It includes a div that loops through title and data. Inside the div, there is a search filter and content that renders in p tags. The p tags also go through a loop.

Take a look at the code below:

<div>
    <div v-for="(item) in data" :key="item.id">
        <div>{{item.title}}</div>
        <input type="text" v-model="search" />
        <div v-for="(content, j) in filteredLists" :key="j">
            <p v-for="(con, k) in content" :key="k">{{con}}</p>
        </div>
    </div>
</div>

Here is the provided data:

search: "",
data: [
    {
        id: 1,
        title: "Devsrc",
        content: {
            id: 1,
            details: ["ONE_DEV_EMP1", "ONE_DEV_EMP2"]
        }
    },
    {
        id: 2,
        title: "Devsrc2",
        content: {
            id: 2,
            details: ["TWO_DEV_EMP1", "TWO_DEV_EMP2"]
        }
    },
    {
        id: 3,
        title: "Devsrc3",
        content: {
            id: 3,
            details: ["THREE_DEV_EMP1", "THREE_DEV_EMP2"]
        }
    }
]

Check out this computed property:

filteredLists() {
      return this.data.map(item => {
       return item.content.details.filter(detail => {
           return detail.toLowerCase().match(this.search);
       })
      });
    },

The goal here is to only render details for items where the ID matches the content ID.

Answer №1

Transform filteredLists() into a method rather than a computed property initially.

<div>
    <div v-for="(item) in data" :key="item.id">
        <div>{{item.title}}</div>
        <input type="text" v-model="search" />
        <div v-for="(content, j) in filteredLists(item.id)" :key="j">
            <p v-for="(con, k) in content" :key="k">{{con}}</p>
        </div>
    </div>
</div>

function filteredLists(id) {

  let term = this.search.trim().toUpperCase();
  let scoped = this.data.filter(item => { return parseInt(item.content.id) === parseInt(id) });

  if(term.length > 0) {
    return scoped.filter(item => {
      return item.content.details.find(seek => seek.match(search));
    });
  }

  return scoped;
}

let search = 'EMP2';

let data = [{
    id: 1,
    title: "Devsrc",
    content: {
      id: 1,
      details: ["ONE_DEV_EMP1", "ONE_DEV_EMP2"]
    }
  },
  {
    id: 2,
    title: "Devsrc2",
    content: {
      id: 2,
      details: ["TWO_DEV_EMP1", "TWO_DEV_EMP2"]
    }
  },
  {
    id: 3,
    title: "Devsrc3",
    content: {
      id: 3,
      details: ["THREE_DEV_EMP1", "THREE_DEV_EMP2"]
    }
  }
];

function filteredLists(id) {

      let term = search.trim().toUpperCase();
      let scoped = data.filter(item => { return parseInt(item.content.id) === parseInt(id) });

      if(term.length > 0) {
        return scoped.filter(item => {
          return item.content.details.find(seek => seek.match(search));
        });
      }

      return scoped;
}

console.log(filteredLists(3));

Answer №2

displayFilteredLists() {
  return data.filter(
    function(item) {
      return item.content.details.find(
        function(detail) {
          return detail.toLowerCase().includes(this.query)
        }.bind(this)
      )
    }.bind(this)
  )
}

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

To install the Vue CLI globally, simply type 'npm install -g @vue/cli'. Keep an eye out for any warnings or

When I run the command npm install -g @vue/cli, changed 851 packages, and audited 852 packages in 2m 64 packages are looking for funding 4 vulnerabilities (2 moderate, 2 high) To address all issues (including breaking changes), run: npm audit fix --fo ...

express-session fails to remove sessions from mongodb

account.js (node.js part) const express = require("express"); const router = express.Router(); router.post("/logout", (req, res) => { console.log("session: ", req.session); req.session.destroy(); console.log("session: ", req.session); res.send ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

Several different forms are present on a single page, and the goal is to submit all of the data at

Looking for assistance with combining Twitter and Google data entry at once. Here's the code I've developed: Please guide me on how to submit Twitter and Google details together. <html> <head> <script type="text/javascript">< ...

Vue's TreeView component has been encountering issues with accurately displaying the contents of sub

Currently working on creating a customized TreeView in Vue. Check out my progress in the code here. The issue I'm facing is that the subfolders' content (such as child folder 1) is not displaying correctly. Additionally, collapsing the subfolder ...

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

How to obtain the height of the parent screen using an iframe

Imagine a scenario where a div contains an image that is set to perfectly fit the height of the screen. This setup works flawlessly, with one exception - when placed within an iframe, the height of the div adjusts to match the content's height rather ...

Is it better to verify the data from an ajax request or allow JavaScript to generate an error if the data is empty

Is it better to check if the necessary data is present when handling success data in jQuery, like this? success: function (data) { if (data.new_rank !== undefined) { $('._user_rank').html(data.new_rank); } } Or should you just l ...

Issues with syntax in AJAX programming can be a significant road

I have a function linked to an onclick button event. This function sends data via ajax to another php file. Everything was working smoothly until I tried to add an IF statement to the 'success' section, which would receive true or false from an e ...

Is there a way to target a button within an anchor tag without relying on a specific id attribute?

On my webpage, I have buttons that are generated dynamically using PHP from a MySQL table. Each button is wrapped in an anchor tag and when clicked, it triggers a Javascript function to carry out multiple tasks. One of these tasks requires extracting the ...

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

Using React and Material UI to create a table filtering system with checkboxes

I'm currently developing a filtering feature using checkboxes for a data display in a project utilizing React and Material-UI. Is there a custom solution available within Material-UI? If not, what steps should I take to achieve this? As I am rel ...

Attach onClick event when employing a higher order component

Just getting started with React and I have a question. After following some blog posts, I was able to create a page using higher order components and componentDidMount to fetch data from an API and display it. Everything works smoothly and the code looks ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Tips for choosing an option in a form using Selenium with JavaScript

I am currently in the process of automating some tests for a specific form, and I have successfully automated all steps except for selecting an option from a dropdown menu using JavaScript. Here is my code: const {Builder, By, Key} = require("sel ...

The manner in which sessionStorage or localStorage is shared between different domains

I am looking to persist data across different domains using sessionStorage or localStorage. How can I achieve this? The data needs to be shared between a Vue project and a React project. English is not my strong suit, so I hope you are able to understand ...

How can a particular component within the DOM be referenced and stored for future use?

The issue at hand: My current project involves developing a file tree with a specific feature called "Selected Folder." This functionality allows users to designate a target for creating new files and folders within the tree. (I'm using Vue in Electr ...

Issue with JQuery Validation: Some checkbox values are not being successfully posted

Currently experiencing issues with validating checkboxes. Utilizing the jQuery plugin validation found here: The scenario is that there are three checkboxes and at least one of them must be checked. The original form code for these checkboxes is as follow ...

Creating customized JavaScript using jQuery for Drupal 7 Form API

Currently, I am working on developing a custom form using Drupal 7 with form API and a tableselect that includes checkboxes. I have some specific constraints for selecting the checkboxes that I intend to implement using jQuery. I created a function for han ...