Sort through the array using a separate array in Vuejs

I am currently working with two arrays:

 {
"products": [
    {
        "name": "Jivi",
        "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche",
        "frequency": ["1", "2", "8"]
    },
    {
        "name": "Adynovi",
        "Hint": "40-50 IE/kg 2x/Woche im Abstand von 3-4 Tagen",
        "frequency": ["2", "6", "7"]
    },
    {
        "name": "Esperoct",
        "Hint": "\"50 IE/kg \nalle 4 Tage\"\n",
        "frequency": ["7"]
    }
],
"haufigkeit" : [
    {
        "name": "1x / Woche",
        "id": 1,
        "value": 52.1428571429
    },
    {
        "name": "2x / Woche",
        "value": 104.2857142857143,
        "id": 2
    }
]
}

In my Vuejs application, I have a select dropdown where the products.name are dynamically rendered.

 <select v-model="selectFrequency">
        <option v-for="(level1,index) in dataJson.products"
                v-bind:value="level1.frequency">{{level1.name}}</option>
      </select>

When a user selects a product like Jivi, I want to compare the numbers in the frequency array of the selected product with the id in the haufigkeit array. If there is a match, I need to display the corresponding name from the haufigkeit array.

Here is the code snippet I have been working on:

computed:{
selectFrequency:function(){
    let results= this.haufigkeit.filter(array=>array.every(item => this.products.filter(group=>group.frequency.includes(item))));
}
}

For the past two days, I have encountered an error stating

cannot read property 'every' of undefined
. Can someone please guide me on where I might have made a mistake?

Answer №1

Edit: After some more understanding, it seems like this solution should fit your needs: https://jsfiddle.net/q9grc04s/

By selecting a product, you will be able to see all haufigkeit values that have an ID corresponding to the selected frequency.

<template>
<div>
  <div>
    <select v-model="selectedFrequency">
      <option
        v-for="(level1, i) in products"
        :key="i"
        :value="level1.frequency"
      >
        {{level1.name}}
      </option>
    </select>
  </div>
  <div>
    <h1>Haufigkeit Matches:</h1>
    <ul v-if="haufigkeitMatches">
      <li v-for="match in haufigkeitMatches">{{ match.name }}</li>
    </ul>
  </div>
</div>
</template>

<script>
export default {
  data: {
    selectedFrequency: [],
    products: [
        {
            name: "Jivi",
            Hint: "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche",
            frequency: [1, 2, 8]
        },
        {
            name: "Adynovi",
            Hint: "40-50 IE/kg 2x/Woche im Abstand von 3-4 Tagen",
            frequency: [2, 6, 7]
        },
        {
            name: "Esperoct",
            Hint: "\"50 IE/kg \nalle 4 Tage\"\n",
            frequency: [7]
        }
    ],
    haufigkeit : [
        {
            name: "1x / Woche",
            id: 1,
            value: 52.1428571429
        },
        {
            name: "2x / Woche",
            value: 104.2857142857143,
            id: 2
        }
    ]
  },
  computed: {
    haufigkeitMatches(){
        return this.haufigkeit.filter(x => this.selectedFrequency.includes(x.id))
    }
  }
}
</script>

Note: Apologies for multiple edits, I'm still getting used to the stackoverflow editor. The link to the JS fiddle provided is a functional solution for your issue.

Answer №2

If you want to check for the inclusion of an object in an array using Javascript, you can use a specific function. In the example below, I am retrieving the IDs from the 'haufigkeit' array that match the frequencies of the products.

var data = {
    "products": [
        {
            "name": "Jivi",
            "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche",
            "frequency": ["1", "2", "8"]
        },
        {
            "name": "Adynovi",
            "Hint": "40-50 IE/kg 2x/Woche im Abstand von 3-4 Tagen",
            "frequency": ["2", "6", "7"]
        },
        {
            "name": "Esperoct",
            "Hint": "\"50 IE/kg \nalle 4 Tage\"\n",
            "frequency": ["7"]
        }
    ],
    "haufigkeit" : [
        {
            "name": "1x / Woche",
            "id": 1,
            "value": 52.1428571429
        },
        {
            "name": "2x / Woche",
            "value": 104.2857142857143,
            "id": 2
        }
    ]
};

var result = [];
function selectFrequency(){

    data.products.forEach(elem => {
      
        elem.frequency.forEach(fre =>{
            var arr = data.haufigkeit;
            if(arr.some(arr => arr.id == fre))
                result.push(fre);
        })
    });
    return result;
}

console.log(selectFrequency());

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

Invoke Office script from beyond MS Excel WebApp

Within the Excel WebApp on Office 365, users have the ability to incorporate Office Scripts through the "Automate" tab. These scripts utilize JavaScript syntax and can automate Excel functions similar to a VBA macro, specifically designed for the Excel Web ...

The command "npm run watch" is hanging

Previously everything was running smoothly, but now I seem to be facing an issue with the npm run watch command. It gets stuck at this point: 10% building 1/1 modules 0 active webpack is watching the files… 12% building 19/27 modules 8 active ...View.vu ...

Converting PHP variables to JavaScript using AJAX and XML communication

In order to gain a deeper understanding, I am determined to tackle this task without relying on jQuery. This means I am willing to reinvent the wheel in order to fully comprehend how it functions. My research has led me to believe that AJAX is the key to a ...

transforming a text input into unadorned plain text

Currently, I am in the process of creating a small HTML form that consists of a single textbox input. Once the user enters text into this textbox and clicks on a button located at the end of the page, I would like the textbox to transform into normal plain ...

AngularJS UI.Router ActiveState implemented with a dropdown menu feature

I am currently working on creating a menu with dropdown functionality for multiple links within my application. My goal is to have the dropdown menu display as "active" when one of the links below is active. I have managed to make either the link in the ...

Guide on sending AJAX requests from Javascript/React to Python REST API and receiving data

In my project, I have developed the front end code using React. There is a simple form where users can input their name, title, department, and other basic string fields. Upon hitting submit, JavaScript triggers an AJAX request to my REST API which is impl ...

Sending a function along with event and additional arguments to a child component as a prop

I've managed to set up a navigation bar, but now I need to add more complexity to it. Specifically, I have certain links that should only be accessible to users with specific permissions. If a user without the necessary permissions tries to access the ...

Refresh the component data according to the vuex state

In order to streamline my workflow, I am developing a single admin panel that will be used for managing multiple web shops. To ensure that I can keep track of which website I am currently working on, I have implemented a website object in my vuex state. Th ...

Combining multiple directories into a single output using the rollup command

Alright, let's talk about my directory setup: mods/ -core/ --index.js --scripts/ ---lots of stuff imported by core/index Currently, the typical rollup process works smoothly if you want to create something like mods/core/index.min.js. However, I ha ...

The server is indicating that the validation for the user has failed due to the required field "foo" not being provided in the Node.js

An error message was received with the following details: "User validation failed: email: Path email is required., display_name: Path display_name is required." The error name returned is: ValidationError. The AJAX call code snippet is as follows: f ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

Issue with CORS policy preventing Laravel 9 from running properly (XMLHttpRequest access blocked)

I am currently working on developing a frontend web application using Vuejs, and I need to fetch data from an API built with Laravel 9. However, when trying to access the data from the frontend, I encountered the following CORS-related error in the browser ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

I'm baffled as to why this code isn't functioning properly

My current script seems to be malfunctioning for some reason. I'm using a combination of express, socket.io, jade, and node.js in this setup. Below is the script I am working with: var socket = io.connect(); function addMessage(msg) { var currentDa ...

The React Context Value keeps coming back as undefined every time

As a beginner working with contexts, I am taking it slow. Recently, I came across logging Providers to test the value and encountered a constant 'undefined' result. To troubleshoot, I tried moving them side by side in the code to see if it makes ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Issue with continuous loader malfunction

I integrated a 3-second mini-loading animation on my website. It shows up every time I refresh the site or navigate to another page. The issue I'm facing is that once I add the loading section, it never stops (it should only last for 3 seconds). Usua ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...