A guide on how to apply filtering to an array in Vue using another array

Currently, I have two arrays of objects: one is named submodules and it contains a children array within it. My goal is to filter these children arrays based on another array called accessed.

new Vue({
  data: {
    submodules: [
      {
          type: "something1",
          children: [
              {
                  name: "new_sth1",
                  value: "new_sth1"
              },
              {
                  name: "new_sth2",
                  value: "new_sth2"
              }
          ]
      },
      {
          type: "something2",
          children: [
              {
                  name: "new_sth3",
                  value: "new_sth3"
              },
          ]
      },
      {
          type: "something3",
          children: [
              {
                  name: "new_sth4",
                  value: "new_sth4"
              },
              {
                  name: "new_sth5",
                  value: "new_sth5"
              },
              {
                  name: "new_sth6",
                  value: "new_sth6"
              },
          ]
      },
    ],
    accessed: [
      {value: 'new_sth1'},
      {value: 'new_sth2'},
      {value: 'new_sth3'},
      {value: 'new_sth4'},
    ]
  }
})
<div class="row">
    <div class="col-6 mt-3" v-for="item in submodules.filter(submodule => accessed.some(accessedItem => accessedItem.value === submodule.children[0].value))">
        <div class="card" style="min-height: 260px">
            <div class="card-header" style="background: #757575;color: white">
                {{item.type}}
            </div>
            <div class="card-body">
                <ul class="nav nav-pills nav-stacked mb-0 pb-0">
                    <li style="width: 100%;cursor: pointer" class="navbar my-0 py-0" v-for="child in item.children">
                        <a style="color: black" :href="'/'+child.value">
                            <span class="text-right navbar-text">{{child.name}}</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

I am struggling to filter the submodules array using the values from the accessed array. If you have any suggestions or ideas, please feel free to share them with me.

Answer №1

You can utilize the computed property to selectively filter the elements in the submodules array based on the accessed attribute.

Learn more about computed properties in Vue.js

CodeSandbox link: The code is unstyled since I have not installed Bootstrap.

computed: {
    getFilteredResult() {
      return this.submodules.reduce((acc, curr) => {
        const children = curr.children.filter(({ value }) => {
          return this.accessed.find((x) => x.value === value);
        });
        acc.push({ ...curr, children });
        return acc;
      }, []);
    },
  },

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

Why are JS & jQuery's inArray() and indexOf() functions not functioning correctly when indexes are strings?

Here is an example of an array: var arr = []; arr['A string'] = '123'; arr['Another string'] = '456'; I am attempting to find the index of either '123' or '456'. Both methods below are returnin ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one. Here's an example of what I'm looking ...

Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment. I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values). Without further ado: As an example, here is w ...

XML is struggling to load content when using ajax requests

I am attempting to utilize ajax to load an xml file. I have made adjustments to the sample code provided by W3Schools <html> <head> <script> function showBus(str) { if (str == "") { ...

Transforming JQuery text upon selecting preloaded content with fire

When I copy the first name into the last name field, everything works fine for new names on the page. However, once a few names have been entered and the browser starts showing a history of names, the function doesn't work anymore if a pre-filled or o ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

Installing v8-profiler on Windows 8 (64 bit) through npm: a step-by-step guide

The v8-profiler module is widely recognized as the go-to tool for identifying memory leaks in node.js applications. However, attempting to install it with npm install v8-profiler results in an error message related to compatibility issues between 32bit an ...

What strategies can I use to prevent the need to create new instances of my service and repository for every

Currently, I am delving into the world of JavaScript using the Express.js Framework. My current learning project involves creating a simple restaurant application to grasp the ins and outs of CRUD operations related to ingredients. I have meticulously craf ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Navigating through a Single Page Application (SPA) can be achieved without

Can the CSS (Level 4) @document rule handle URLs that have the # symbol or include query parameters? For those who are not familiar with this topic Currently, only Firefox supports this feature with the @-moz-document prefix. If other browsers start supp ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

Vue: Implementing Data Refresh in Store Post-Login

I am encountering an issue with the data store "menus" not updating after a login. It seems that the object "loggedInUser" is not set before calling "getMenus". I'm unsure of what mistake I might be making here. PS! While debugging in Chrome, I notic ...

Upgrade your function to utilize Firebase V9 with Next.js framework

I recently updated my project to use version 9 of firebase, and since then, I've been encountering some code errors that I'm struggling to resolve. The previous function had the following structure, but now I need to update it to work with the n ...

Decipher the communications sent by the server

I have been working on a hybrid application using vuejs and ruby on rails, and I am trying to figure out how to translate the error messages that are generated by the server. While I have managed to translate the titles easily with a method, I am strugglin ...

Scrolling to specific ID scrolls only in a downward direction

I have been using fullpage.js for my website and I am facing an issue. When I create a link and connect it to an id, everything works perfectly. However, I am unable to scroll back up once I have scrolled down. Here is the HTML code: <a href="#section ...

Mastering the art of seamless navigation within a single page through the magic of

I have two HTML pages: "Login.html" and "index.html". Instead of a normal href linking, I want the user to navigate to "index.html" when they click on the login button. Furthermore, I want the index page to be displayed within the codes of login.html, cre ...

Reactive property cannot be defined on an undefined, null, or primitive value within the context of Bootstrap Vue modal

Can someone please assist me with this error message? It says "app.js:108639 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value." I encountered this error while working with a Bootstrap Vue modal. Here is a snippet of my code: ...

Create an array of arrays within a loop using TypeScript

My application contains an object with dates and corresponding time arrays. The console log output is displayed below: 32: { 1514160000: Array [ 1200, 1500 ], 1514764800: Array [ 1200, 1500 ], 1515369600: Array [ 1200, 1500 ], 1515974400: Array [ 700, 12 ...

I'm baffled by the constant undefined status of the factory in AngularJS

I have encountered an issue where I defined a factory that makes a get request, but when I inject it into a controller, it always throws an undefined error. Below is the code for the factory: (function() { 'use strict'; var app = angul ...