Home > Blockchain >  I want to check about the pushed name in the object if its found in the array it won't be re-pu
I want to check about the pushed name in the object if its found in the array it won't be re-pu

Time:02-20

this is html code

<body>
    <section>

        <h1>client profile informations</h1>
        <div  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 is pushed every time whatever the condition

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

    <script> 
**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});    
        }

**empty the input field**

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

CodePudding user response:

addio() isn't actually checking whether the entry already exists in this.grades[]. It only compares newstu (the newly entered student name) to this.grades.name, which doesn't exist because this.grades is an Array.

One solution is to use Array.prototype.find() to search this.grades[] for a matching entry. Every callback to find() receives an array entry, which can be used to compare the entry's name property against this.newstu. If the entry is not found, find() returns undefined, so you can use the call in an if-statement:

if (this.grades.find(grade => grade.name === this.newstu)) {
  // already exists...ignore

} else {
  // new entry
  this.grades.push({ name: this.newstu, gpa: this.newgpa })
}
  • Related