How can you compare array values in Vuejs while iterating through them?

WelcomeWorld.vue

<template>
      <div>
        <div v-for="box in boxes" :key="box.sname">
          <BaseAccordian>
            <template v-slot:title>{{ box.sname }}</template>
            <template v-slot:content>
              <div v-for="paint in paints" :key="paint.tname" class="line">
                <List :content="matchingdata" :sname="box.sname" />
              </div>
            </template>
          </BaseAccordian>
        </div>
      </div>
    </template> 

    <script>
    import BaseAccordian from "./BaseAccordian.vue";
    import List from "./List.vue";
    export default {
      name: "WelcomeWorld",
      components: {
        BaseAccordian,
        List,
      },
      data() {
        return {
          boxes: [
            {
              sname: "apple",
            },
            {
              sname: "orange",
            },
            {
              sname: "kiwi",
            },
            {
              sname: "mango",
            },
          ],

          paints: [
            {
              tname: "a",
            },
            {
              tname: "b",
            },
            {
              tname: "c",
            },
            {
              tname: "d",
            },
            {
              tname: "e",
            },
          ],

          matchingdata: [
            {
              matchid: "1",
              OverallStatus: "ok",
              sname: "mango",
            },
            {
              matchid: "2",
              OverallStatus: "notok",
              sname: "kiwi",
            },
          ],
        };
      },
    };
    </script>

BaseAccordion.vue

    <template>
      <div class="wrapper">
        <div class="accordion">
          <input type="checkbox" @click="toggleItem" />
          <h2 class="title">
            <slot name="title"></slot>
          </h2>
        </div>
        <div v-show="show" class="content">
          <slot name="content"></slot>
        </div>
      </div>
    </template>
    <script>
    export default {
      components: {},
      data: function () {
        return {
          show: false,
        };
      },
      methods: {
        toggleItem: function () {
          this.show = !this.show;
        },
      },
    };
    </script>

List.vue

    <template>
      <div class="">
        <div
          v-for="match in matchingData"
          :key="match.matchid"
          :class="{
            green: match.OverallStatus === 'ok',
            red: match.OverallStatus === 'notok',
          }"
        >
          {{ match.OverallStatus }}
        </div>
      </div>
    </template>
    <script>
    export default {
      components: {},
      props: {
        content: {
          type: Array,
          required: true,
        },
        sname: {
          type: String,
          required: true,
        },
      },
      data: function () {
        return {};
      },
      methods: {},
      computed: {
            matchingData() {
      return this.content.filter((a) => {
        if (a.sname === this.sname) {
          return true;
        } else {
          return false;
        }
      });
    },
      },
    };
    </script>
    <style scoped>
    </style>

I three arrays called matchingdata,boxes,paints array based on this three arrays, I am attempting to filter the array.(nested v-for)

Now, I aim to cycle through the matchingdata array by comparing it with sname in the boxes array. The common value between matchingdata and boxes array is ""sname""

I tried the above logic and encountered an issue with the computed property.

Expected Result:-

In List.vue component, I have {{ match.OverallStatus }} where that field, I want to display (from the matchingdata array) when the user clicks on the checkbox.

Taking the ""sname"" the common value from the matchingdata array and the boxes array

code: https://codesandbox.io/s/damp-pine-27s2kn?file=/src/components/List.vue

Answer №1

When passing the sname property as a string through a prop to your List.vue component, make sure to use that string in your filter function.

retrieveData() {
   return this.items.filter((item) => item.sname === this.sname)
},

I tested this on your codesandbox link and it produced some results - but I'm not entirely sure of your desired outcome so I can't confirm if this is what you want.

Just a reminder: the 'filter' function creates a new array. It doesn't output 'true/false', which it seems like you might be trying to achieve.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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

Is it necessary for me to be concerned with clearing out sizable objects in Node.js, or should I trust the garbage collector to handle

Recently, I encountered a memory issue with my node.js API while hosting it on Heroku's free version with only 512MB RAM. As the traffic increased over the weekend, I started receiving memory errors from Heroku due to exceeding limits. Despite searchi ...

Enhancing a JQuery Element to Suit Your Needs

Is it recommended to enhance a JQuery element with custom methods? For example: var b = $("#uniqueID"); b.someMethod = function(){}; Additional Information Let me explain further, I am developing a JavaScript application that binds JSON data to local J ...

Axios is repeatedly making GET requests to an incorrect endpoint

I have set up axios to make requests to my express backend hosted on localhost:8081 src/htpp/index.js import axios from 'axios' export default axios.create({ baseURL: 'http://localhost:8081/api/', timeout: 1000, headers: {&apos ...

What could be causing the hover effect to not work on other elements within the div?

I am working on creating a card that displays only the image when not hovered, but expands and reveals additional information in a div to the right of the image when hovered. Unfortunately, when I hover over the image and then move towards the adjacent div ...

Unable to get the deletion functionality to work for Dropzone.js and PHP script

I am currently using dropzone to handle file uploads. My goal is to delete the files on the server when the user clicks on the removeLink. I have implemented an Ajax function that calls a .php site for this purpose. However, I am facing an issue where I am ...

packages have gone AWOL in the Bitbucket pipeline

Hello everyone. I am currently working on setting up a pipeline for my nextjs-project and I've encountered a problem. I have a specific function for generating buildId # scripts/generate-build-id.js const nextBuildId = require('next-build-id&ap ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

Guide on combining two JSON Array objects in Nodejs

Is there a way to merge two JSON Array objects together using Node.js? I am looking to combine obj1 + obj2 in order to create a new JSON object: obj1 = [ { t: 1, d: 'AAA', v: 'yes' }, { t: 2, d: 'BBB', v: 'yes& ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...

Creating interactive comments in Vue 3 using dynamic rendering

Is there a way to properly display a dynamic comment in Vue 3? I attempted using v-html, but it's not working as expected in my scenario. Here is the example: https://i.sstatic.net/ddX39.png <template> <!-- Method 1: not displaying correctl ...

Rails inspired tag selection tool akin to Stack Overflow

In my Rails application, I am looking to implement a tagging system for models. I want to create a tag selection feature similar to Stack Overflow where I can type in a tag like 'rails' and a drop-down list of options containing that tag will app ...

Stop the Text Table from being highlighted

My webpage includes a dynamic table where users can select multiple rows. jQuery events and CSS are utilized to provide visual feedback when a row is selected. However, pressing the shift key sometimes causes text to become highlighted, which is not idea ...

Display an image from the API that rotates when hovered over with the mouse

Currently, I am fetching data from pokeapi.co and dynamically inserting it into a table. This data includes various stats and an image. My goal is to make the image rotate when hovered over. While creating the table, I added an id="pokeImage" dynamically. ...

The onChange functionality of the Formik Field API is not compatible with a child component

I am currently facing an issue with validating a material-ui-dropzone component within the Formik Field API as a child component. When I try to upload a file, I encounter the following error: TypeError: can't access property "type", target is undefine ...

Access the values within an array located inside a data object by utilizing ng Repeat function

Attempting to utilize ng repeat for extracting values from an array. Below is the HTML code: <ion-list ng-repeat="item in locationresult"> <ion-item > <ion-checkbox ng-repeat="innerItem in item.loc[$index]"> ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...

Toggle class on element based on presence of class on another element

If I have 4 boxes and the user is required to choose one. I aim to assign an active class to the box that the user clicks on. However, if the user selects another box, I want to remove the class from the first clicked box and apply it to the newly clicked ...

ID of the Radio button that was most recently selected

My table contains multiple rows, each with a Radio button in the first column: <table class="table table-condensed span8" id="AllocationTable"> <thead> <tr> <th title="Entity to Allocate" style="width: 30%"> ...

Looking to Move the Image Up?

I've been experimenting with creating a grid layout where the bottom image will move up until it is 10px away from the image directly above it. However, no matter what I attempt, the spacing seems to be based on the tallest image rather than the one a ...

One way to send image data from the front end to the back end using AJAX

Client-Side JavaScript: var userInfo = { 'username': $('#addUser fieldset input#inputUserName').val(), 'email': $('#addUser fieldset input#inputUserEmail').val(), 'fullname': $('#addUser f ...