Implementing array.includes in a Vue.js project

I am currently working on a Vue app where I need to display or hide values based on selected options from a multiselect. So far, everything is functioning correctly with the select and the corresponding function it calls.

However, I encountered an issue when trying to use includes within my v-if statement in the HTML. It prompted an error saying it cannot read properties of undefined when trying to access includes.

I suspect there might be an issue with how I'm calling the includes method or the testArray variable here. Can anyone provide insight into this problem?

new Vue({
  el: "#app",
  props: { 

  },
  components: {Multiselect: window.VueMultiselect.default},
  data: {
    tiers:[
      {name: "test tier"}
    ],
    selectedTier: [],
    values: [
      {name: "adam", tier: "test tier"},
      {name: "sam", tier:"none"}
    ]
  },
  checkTier(){
    console.log(this.selectedTier);

    let testArray = [];

    this.selectedTier.forEach(fields => {
      this.testArray.push(fields.name);
    });
    console.log(this.testArray);
  },
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2c2f3f77372f362e33293f363f392e1a68746b746a">[email protected]</a>"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbcdcede96d6ced7cfd2c8ded7ded8cffb89958a958b">[email protected]</a>/dist/vue-multiselect.min.css">


<div id="app">

<div class="uk-width-2-10" style="position:relative;">
    <multiselect
      v-model="selectedTier"
      :options="tiers"
      :multiple="true"
      :close-on-select="true"
      placeholder="All Tiers"
      label="name"
      track-by="name"
      @input="checkTier"
    ></multiselect>
</div>

<div v-for="value in values">
  <div v-if="testArray.includes(value.tier)">
    <p>Working</p>
  </div>
</div>

</div>

Answer №1

As Chalie Schliesser mentioned in the discussion:

Add it as a data property (in data()) and append to it just like you are currently doing

When it comes to creating a unique array, there are several methods to achieve this:

  1. const unique = (array) => [...new Set(array)];

You can then use the unique function to obtain a unique array.

  1. You can create a function that accepts an array and a specific key of concern and iterate through them. Let's assume our array looks like this:
const array = [
  {title: 'Fancy pants'},
  {title: 'New fancy title'},
  {title: 'Fancy pants'}
]

then we can implement something similar to this:

const removeDuplicates = (array, key) => {
  const check = {};
  const res = [];

  array.forEach(element => {
    if (!check[element[key]]) {
      check[element[key]] = true;
      const label = element.title;
      const value = element.title.toLowerCase();
      const search = element.title.toLowerCase();
      res.push({ label, value, search });
    }
  });
  return res;
};

Executing:

console.log(removeDuplicates(array, 'title'))

should generate the following result:

const array = [
  {title: 'Fancy pants'},
  {title: 'New fancy title'}
]

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

How can one leverage Node JS to effectively manage events?

Is it considered a best practice to utilize events for communication between functions within ExpressJS? If so, what is the proper way to send arguments along with my emit event? ...

Trigger a JQuery function to run upon the pressing of the Enter key within a textbox

$(document).keypress(function(e) { if(e.which == 13) { $("#submitButton").click(); } }); That's how I'm triggering my function when the Enter key is pressed anywhere on a page, but it conflicts wi ...

Navigate to the appropriate Angular route using HTML5 mode in Rails

After removing the '#' symbol in angular by using html5Mode, everything seemed to work fine. However, upon refreshing the page, it started looking for the template in Rails instead of Angular, resulting in a "template not found" error. Angular R ...

Combine various puppeteer-generated PDF buffers from different URLs into a consolidated PDF file and deliver it back to the user

Attempting to combine multiple PDF buffers from puppeteer into a single file has proven to be quite challenging. Despite trying different solutions, the output still indicates that it's unable to load, with Adobe, Chrome, and Fox-IT all suggesting cor ...

Issue with a stationary directional light tracking the movement of a rotating object and/or changes in the camera perspective

I've been facing a challenge in implementing a day-night cycle with a directional light in an Earth model using custom shaders. Everything seems to work fine with the night and day maps, as well as the light, as long as I don't manipulate the cam ...

Unicode Cookie Functionality in ExpressJS

Is there a solution for encoding unicode values in cookies using expressjs? For instance, when a user is utilizing the Spanish language setting, a cookie might be encoded with the user's name, like "José" For example: res.cookie('user', ...

Has the jQuery plugin object misplaced a variable?

I am in the process of developing a basic plugin using jQuery. My current approach involves creating private functions and storing variables within the jQuery object itself. (function($) { var somePrivateFn = function() { alert(this.x); } ...

Iterate over the object to verify if the field contains an empty array, then output null

Looking for help with handling empty arrays in an object: productDetails: { cislife: [], prime: [] } Is there a way to have null returned instead of an empty array if no values are available? For example, I'd like to determine if either t ...

Designing a navigational sidebar featuring clickable links to specific locations on Google Maps

I'm currently utilizing a map script created by Derek Ender that integrates with Google Fusion Tables to display locations on a map. While the script is functioning well, I have received a request to make the sidebar list of locations clickable. The ...

The placement of term.js is always at the bottom of the body

Seeking help with JavaScript as a beginner, I am facing issues with placing an element in my project. Although I can easily open terminals and write to them, every time I create one, it gets appended at the end of the body. I referred to this example for ...

Setting a scope variable in an isolate scope from a link function can be achieved by accessing the

In my attempt to assign a variable within an isolate scope, I am encountering difficulties accessing the variable set in the linked function. Surprisingly, I can access the controller's variable without any issues. app.directive('myDir', fu ...

GET method returns an empty array in the express node server

app.get('/:user/:tag', function (req, res) { fs.readdir( 'api'+path.sep+req.params.user, function (err, files) { var tweets=[]; for (var i =1, j=files.length ; i <j; i++) { fs.readFile('api'+path.sep+ ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

The filter plugin in Nuxt.js with Vue integration is malfunctioning

I've been attempting to implement a Vue filter in Nuxt, but I'm having trouble getting it to function properly. plugins/filters.js import Vue from 'vue' /** Vue Filters Start */ Vue.filter('truncate', function (text, length, ...

Tips and tricks for retaining the collapsed state upon reloading Bootstrap 5

Just diving into the world of bootstrap and javascript. How do I save the collapsed state to make sure it stays even after refreshing the page? <p> <button class="btn btn-primary" type="button" data-bs-toggle="collapse&q ...

Discovering the data-id value in an HTML element by clicking it with JavaScript and returning that value through a for loop

this is my unique html content <ul class="dialogs"> {% if t_dialogs %} <li class="grouping">Today</li> {% for item in t_dialogs %} <li class=&qu ...

How can I effectively retrieve the JWT in a node environment?

I've successfully set up JWT authentication using Node.js. After the user signs in, Node.js generates a JWT and sends it back to be stored in the localStorage. However, I've encountered an issue when trying to access this token within the express ...

Query the Firebase database in Angular2 to locate the latitude and longitude values that are nearest to the user's current coordinates

I am working with a database table named locations, which contains a list of places along with their corresponding lat/long coordinates. Additionally, I am utilizing geolocation to retrieve the user's current lat/long. My goal is to identify the loc ...

Efficiently transferring components of a JavaScript project between files

For the first time, I am creating an npm package using ES6 and Babel. However, I am facing difficulties in connecting everything together so that it can be imported correctly by the end user. The structure of my build (output) folder is identical to src: ...

Issues with integrating chart.js in Laravel 7: Element #app not found?

Currently, I am utilizing chart.js to display the statistics of reviews and messages for a user. However, I have encountered issues with the scripts. While the stats are functioning correctly, an error message stating Cannot find element: #app is appearing ...