Retrieve a distinct property of an element from an array of objects fetched from an API using Vue 2

I successfully retrieved an array of objects from an API in mounted within Vue. The array consists of various objects with properties such as author, genre, poster, title, and year.

0:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

1:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

2:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

...

I have a <select> element that I want to populate with the unique genres present in the array mentioned above. However, I do not want any genre to be repeated.

<div class="select-genre">
    <label for="genre">Genre</label>
    <select id="genre" name="genre">
        <option value="">Select</option>
        <option v-for="(element, index) in cds" :value="cds.genre">{{ element.genre }}</option>
    </select>
</div>

The current implementation lists every genre multiple times due to repetitions. My approach involves filtering out duplicate genres from the original array to create a new array containing each genre only once. However, the issue arises when the original array refreshes itself post-filtering, making it challenging to generate the desired result.

if (this.cds.length == 10) {
    const genres = this.cds.filter((element) => {
        return element.genre != element.genre;
}

To address this problem, I set up a conditional statement to trigger the filtering process only when the original array contains exactly 10 elements. Following the filter operation, I assign the filtered genres to a separate variable and log its contents to prevent data manipulation.

this.genreArray = [...genres];
console.log('Genres', this.genreArray);

My intention was to store the unique genres in a dedicated array (genreArray) after checking for duplicates per element. However, it seems there might be a flaw in my logic. Can you spot where I went wrong?

Answer №1

Your filtering logic needs improvement. The current condition element.genre != element.genre will always be false as it compares the same element with itself.

A better approach would be:

if (this.cds.length == 10) {
    const genres = {};
    this.cds.forEach((element) => {
       if(!genres[element.genre]) {
          genres[element.genre] = element;
       }
    });
}
this.genreArray = Object.values(genres);

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 to utilize View as a substitute for the div tag in your Web Project

Undoubtedly, when working on a web project, it is common practice to use the div element like this: <div> sample text </div> However, using div in React Native can lead to errors: <View> sample text </View> Is there a way to ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully funct ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

What is the best way to implement a sliding animation for a toggle button?

Currently, I am working on a toggle bar element that is functioning correctly in terms of styling the toggled button. However, I would like to add more animation to enhance the user experience. The concept is to have the active button slide to the newly s ...

Is transforming lengthy code into a function the way to go?

I have successfully implemented this code on my page without any errors, but I am wondering if there is a more concise way to achieve the same result. Currently, there is a lot of repeated code with only minor changes in class names. Is it possible to sh ...

Locate the kth smallest value that results from subtracting two elements within a sorted array

If I have an array that is sorted with a length n where 1 < n <= 1e5, how can I efficiently find the kth smallest difference between two elements in the array? For example, if I have {1,4,9,16} and k is equal to 5, then the differences are {3,5,7 ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

Challenges arise when trying to integrate Vee-Validate's <Field /> component with Vue Multiselect

Seeking assistance from the community, as I seem to be encountering some issues with integrating the Field component with the Multiselect element. Within a Metronic8 wizard that receives input fields from 5 different steps, this specific integration is pro ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

Does binary search maintain its usual efficiency?

Does binary searching remain efficient and effective if an array inherits from an object? ...

Discover the process of loading one controller from another controller in Angular JS

Is it possible to load an entire controller1 from a different controller2, not just a function? ...

Utilize the Material UI SelectField component as a reference for handling onChange events

I'm facing a challenge with my form that contains over 15 SelectField components. I want to avoid creating multiple change handler functions, but I can't figure out how to identify the specific select field that triggered the change event in orde ...

Transform the array of MongoId objects into an array consisting of strings

array ( 0 => "506479dc9a5be1596b1bd97d", 1 => "506479dc9a5be1596b1bd97d", ) The solution that I have implemented involves using `implode` and `explode`, but it proves to be costly and inefficient when executed within a loop. $yut = implode(",", ...

Disable location prompt feature when using AngularJS with Maps API

For my web application, I developed a feature that includes a map with custom markers using Angular loops: <map data-ng-model="mymap" zoom="4" center="[38.50, -95.00]" style="heigth:375px"> <div ng-repeat="item in list"> <marker pos ...

What are the steps to transform my database object into the Material UI Table structure?

I have a MongoDB data array of objects stored in products. The material design format for creating data rows is as follows: const rows = [ createData('Rice', 305, 3.7, 67, 4.3), createData('Beans', 452, 25.0, 51, 4.9), createData ...

Error message: It seems the spatial reference for this ESRI object is missing

Currently, I am utilizing Esri GIS to load the center location from an address. However, I am encountering an issue as I am using a geocoder from Google to obtain longitude and latitude, which is resulting in the following error message: TypeError: this.s ...