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

Utilize JavaScript to substitute font family with a designated class name

After discovering a code snippet that can change font family based on ID, I am interested in implementing it on my website but with a twist - using classes instead of IDs. <!DOCTYPE html> <html> <body> <div class="myP">This is a ...

Altering Image Order Across Various Slides

I have customized a parallax website template that is divided into various sections and slides. I want to incorporate a fixed image sequence on each slide that animates based on the scroll position. With 91 images in the animation sequence, it moves quickl ...

What is the best method to extract specific data blocks from a JSON array in SwiftUI?

Although I am new to SwiftUI and haven't written any code yet, I have a JSON file with nested data that I want to extract and display on a simple view. Is there an easy method in SwiftUI for extracting specific blocks of data from a JSON file? Any gui ...

Transfer information using cURL without the need to refresh the webpage

I am trying to send data to an external API using cURL from a Facebook iframe page (not tab). However, I want to achieve this without reloading the form page. My idea is to use jQuery AJAX to display a "submitting data" message upon form submission and sh ...

"Linking a mouse click event to a specific function within an array using

I'm faced with an issue while trying to bind a click function from an array in my code. It's not responding as expected. Here is a simple example that illustrates the problem: What can I do to solve this issue? var app = new Vue({ el: &apo ...

Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank. The SELECT queries in use are as follows: -- Retrieve all users S ...

What could be the reason for my Angular website displaying a directory instead of the expected content when deployed on I

My current challenge involves publishing an Angular application to a Windows server through IIS. Upon opening the site, instead of displaying the actual content, it shows a directory. However, when I manually click on index.html, the site appears as intend ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

Triggering a JavaScript function when a page is focused due to user interaction

In my project, I have a specific requirement that involves triggering a new window to open when the user clicks on an icon. In this new window, the user should be able to view and edit certain fields. Upon closing the new window and returning to the parent ...

Transform an Angular application built using the Meteor framework to an Express JS-Angular application

Is there an automated or minimalist way to transform an application with a meteor backend and angular frontend to use a backend in Express js and keep the frontend using vue js instead? I have not been able to find any resources or documentation that prov ...

Setting the default dropdown option in Angular

For my latest question, I decided to utilize ng-init. However, upon loading the page, I noticed that there is a blank default option. When I click and select another option, the blank option disappears. How can I remove this initial blank option? Here is ...

Using Selenium with Python to interact with a dynamically generated object that does not have an identifying id or name

Whenever a Right click is performed, an options popup/screen will appear with dynamic content/element. Here is the Options Popup: https://i.stack.imgur.com/TfxpC.png This dynamic content/element will disappear as soon as the mouse is clicked elsewhere o ...

Utilizing Vue.js to place a marker on a PDF document and store its position

I am currently working on a Vue app that requires displaying a pdf document. My goal is to allow users to add markers by clicking on specific locations within the document. Once a marker is added, a form will appear for users to input information. I am loo ...

AngularJS DataGrid export options

Utilizing the angular-datatable plugin, complete with export buttons. You can see an example here: vm.dtOptions = DTOptionsBuilder.fromSource('data.json') .withDOM('frtip') .withPaginationType('full_numbers') // ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

What is the process for integrating tailwindcss into a vite project?

I have recently started using vite version 0.16.6 and I am looking to transition a vuepress website to utilize vite. The main challenge I am facing is figuring out how to set up tailwindcss with vite. In my CSS file named index.css @tailwind base; @tail ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

Injecting a JavaScript object into an HTML string

I am facing an issue with a JavaScript variable I have, which points to a specific DOM element that I want to display somewhere else within the DOM structure. Here is how it is defined: var salesRep = $("ul.map").attr("id","1"); My goal is to pass this v ...

Investigating nearby table cells

I am in the process of creating a game called Dots and Boxes. The grid is filled with numerous dots: <table> <tr> <td class="vLine" onclick="addLine(this)"></td> <td class="box" ...

Retrieve the value with `eventArgs.get_value()` function to obtain the selected text instead of the ID

When I populate a textbox with autocomplete using the code below, it only returns the selected text and not the rowid. Any idea why alert(eventArgs.get_value()) doesn't return the actual ID of the row in SQL? <script language="javascript" type="te ...