I am interested in verifying whether the added name is already in the array before pushing it again. Regardless, the name will still be pushed into the array

this code snippet is written in HTML

<body>
    <section>

        <h1>information about client profiles</h1>
        <div class="madaro" v-on:click.right.prevent>
            <div>
                <input v-model="newstu" type="text">
                <input v-model="newgpa" type="number" @keyup.enter="addio">
                <button @click="addio" > submit</button>
            </div>
            <h1 v-for="grade in grades">
                Student {{grade.name}} has final grade {{grade.gpa}}
            </h1>
        </div>
    </section>

the new name gets added every time no matter what the condition is

    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

    <script> 
**initialize the array**

   grades:[
            {
                name:'pac',
                gpa:'4'
            },
            {
                name:'ray',
                gpa:1.2
            },
            {
                name:'ssy',
                gpa:4.4
            },
            {
                name:'snri',
                gpa:3.5
            },
            {
                name:'safa',
                gpa:1.7
            },
            {
                name:'mohammed',
                gpa:5
            },
            {
                name:'mammt',
                gpa:4.1
            }
        ],
        newgpa:'',
        newstu:''
    },

*the function*

    methods:{
        addio(){
        
        if (this.grades.name === this.newstu) {
            console.log('hyhy');
        } else {
        return this.grades.push({name:this.newstu , gpa:this.newgpa});    
        }

**clear the input fields**

        this.newstu =''
        this.newgpa=''
    }
  }
  </script>
</body>

Answer №1

addio() is lacking a check for the existence of the entry within this.grades[]. It currently only compares newstu (the name of the newly entered student) to this.grades.name, which isn't valid as this.grades is an Array.

An effective solution would be utilizing Array.prototype.find() method to search through this.grades[] for a matching entry. Each callback function to find() receives an array entry, allowing comparison of the entry's name property with this.newstu. If no match is found, find() returns undefined, enabling its usage in an if-statement:

if (this.grades.find(grade => grade.name === this.newstu)) {
  // Entry already exists...ignore
} else {
  // New entry
  this.grades.push({ name: this.newstu, gpa: this.newgpa })
}

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 there a possible method to obtain a smartphone number from a website?

Seeking a solution to retrieve the phone number of a device using HTML 5, JavaScript, or similar technology. Recently, I successfully obtained the coordinates of the device by incorporating the following JavaScript code: <!DOCTYPE html> <html> ...

Unexpected behavior: getElementById returning URL instead of element

I created a function that accepts a thumbnail path as an argument, waits for the bootstrap modal to open, and then assigns the correct path to the thumbnail href attribute within the modal. However, when I use console.log with the element(el), it displays ...

What causes the ignoring of config.proxy in axios requests while working on a webpack project?

My objective I am aiming to make a request using [email protected] with full efficiency through an http proxy (squid). My project is built on Vue and uses the webpack template. I initialized it with vue init webpack proxytest The challenge Despite ...

Is it possible to edit YouTube images or embed YouTube iframes without needing an account?

Recently, I developed a YouTube video sharing system but have encountered some uncertainties. My approach involves extracting the YouTube ID and embedding it in an iframe (I wonder if YouTube permits this). To enhance the visual appeal of the posts, especi ...

Harnessing Spread Syntax with Map and Filter Operations

Recently stumbled upon a fascinating problem that I couldn't wait to share with all of you. Here is the question at hand: [...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7] I managed to successfully solve the initial section up to the fi ...

loading initial data in angularjs

When developing a web application that relies on multiple data sources for every page, what is the most effective way to retrieve the initial data? As observed on Twitter, the tweets that are initially visible on page load are included in the HTML source, ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

preclude any dates prior to the chosen date

I need a solution for a scenario where I have 5 datepickers in sequence. When I select a date on the first picker, all previous dates should be disabled when selecting on the next picker. Additionally, once a date is selected on one picker, the following ...

The transition of a controlled input to an uncontrolled state within a component, along with a partial update to the state

In my project, I have a main component that needs to collect a list of contacts including their name and email: import { useState } from 'react' import AddContactFn from './components/AddContactFn' function App() { const [contacts, ...

When I attempt to use document.execCommand("copy"), the line break does not get applied

I am currently using the following code to create a string and copy it. However, when I paste it as output, the line break is not being applied. function copyToClipboardShipto() { var $temp = $("<input>"); $("body").append($ ...

Troubleshooting: Custom JQuery function not functioning as expected

I am currently facing an issue with the jQuery in my website while trying to implement a portfolio element. It seems to be related to the changePortfolio() function, but I am unsure of how to resolve it. $('.projects a[href^="#"]').on('clic ...

How to Create an Interactive JavaScript Drop Down List for Displaying and Concealing Divs

Looking for some assistance in combining a chained drop-down list with the functionality to show/hide a specific div based on selection. I've come across solutions for each separately, but struggling to merge the JavaScript code (not my strong suit as ...

Having trouble getting event modifiers to work in Vue when added programmatically

Trying to dynamically add events using v-on through passing an object with event names as keys and handlers as values. It appears that this method does not support or recognize event modifiers such as: v-on=“{‘keydown.enter.prevent’: handler}” T ...

Utilizing the Jquery datetimepicker (xdsoft) to dynamically limit the date range between two inline datepickers

Check out the Jquery datepicker plugin available here: We previously had a setup where we could dynamically restrict the date range with two datepickers when text inputs are clicked on. However, the client now wants the calendars to be displayed inline, c ...

Angular 2 ngSubmit triggers unexpectedly on occasions when it is not supposed to

Currently, I am working on developing an Ionic 3 application with Angular 2 and TypeScript. In the app, there is a form that is responsible for sending data to our server. The issue I am facing is that whenever I click on the following button: <butto ...

Obtain the URL from a Span Class located within a table

As I embark on my journey to learn javascript and jQuery, it's clear that my knowledge is quite rudimentary at this point. An attempt to make edits to a script written in Tampermonkey by a friend has led me down a path of extensive Googling with littl ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

AngularJS: handling multiple asynchronous requests

When I make multiple ajax calls in my code, I noticed that the API is only reached after all the ajax calls have been executed. Below you can see the JavaScript code: function test = function(){ var entity = {}; entity.Number = 1; ...

Troubleshooting the encryption of XSSFWorkbook in styles.xml during the save process with Apache POI v3.16

Currently, I am using Apache POI 3.16 with Java version 1.7.0-251 (Unix). I found inspiration in an example provided by @Aniruddh Chandegra on how to create and edit a password-protected excel sheet using Apache POI 3.14 (Link here). [EDIT - Below is the ...

Verify in Mongo if a specific document is already present

Currently in development of my MEAN app, the client-side sends a $http POST request to my API with a JSON array containing soundcloud track data specific to each user. My goal now is to save these tracks to my app database within a 'tracks' table ...