Locate identical values in Vuejs

When working with an array of objects, I need to check if a newly inserted object is a duplicate or not.


        this.duplicate = false;

        for(let item of this.items){
            if(item.id && this.item.name === item.name) {
                this.$notify({
                    group: "notify",
                    text: "Duplicate value!",
                    type: "error"
                });
                this.duplicate = true;
            }
        }

        if(!this.duplicate){
            // Handle post/put request
        }
    

This code currently only works for adding new items (post request). When updating existing items, it always flags them as duplicates.

Answer №1

Prior to adding an item, it is recommended to validate if it already exists

  const newItem; // obtained from request

  const duplicateIndex = this.items
    .map(item => item.name)
    .indexOf(newItem.name);
  // Retrieves the index of an object with the same name as the new item's name 
  // or returns -1 if not found

  // Processing a Post request
  if (newItem.id == null) {
    if (duplicateIndex) {
      this.$notify({
        group: "notify",
        text: "Value already exists!",
        type: "error"
      });
    } else {
      this.items.push(newItem);
    }
  // Handling a Put request
  } else {
    this.items[duplicateIndex] = newItem;
  }

Answer №2

One way to identify duplicate values is by comparing the existing ID of a record with that of other records. If the IDs don't match, and other properties also differ, it can be considered a proper duplicate.

this.duplicate = false;

for(let item of this.items){ 

var existingId=this.item.id || -1; // Using null coalescing operator (??) to assign a default value:


        
        if (existingId!=item.id && this.item.name.toUpperCase().indexOf(item.name.toUpperCase()) == -1) {
           this.$notify({
                group: "notify",
                text: "Duplicate value! ",
                type: "error"
            });
            this.duplicate = true ;
        } else {
             //nothing found
        }        
    }

    if(!this.duplicate){
        // Perform post/put request
    }

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

When attempting to access localhost:3000, the React/NodeJS web page fails to load

As a new developer working with React and NodeJS, I am eager to dive into these technologies: React for the client-side NodeJS for the server-side Webpack for building my files Here is the structure of my project: my-application/ webpack.s ...

Vue 2.0 - Component mounting error: template or render function not defined even though render function is defined

Currently working on a Single Page Application using Vue 2.0. I am bundling all my templates with Webpack from .vue files through Laravel Elixir, laravel-elixir-webpack-official, and laravel-elixir-vue-2. I have gone through numerous existing questions on ...

Is there a way to transfer HTML code from a textarea to CKEDITOR for setData?

My goal is to retrieve data from a textarea element and use it as setData for CKEDITOR. However, instead of receiving the HTML code, I am only getting the code as a string, which is not rendering properly as HTML. Here's the code snippet: CKEDITOR.re ...

What is the proper way to utilize a variable as a field name in a Mongo query within the Meteor framework?

Is there a way to utilize a variable as a field name in a Mongo query within a Meteor application? For instance... This code snippet performs a find operation on my request controllers collection after capitalizing the collection name for the parent id o ...

Having trouble with ReactJS rendering components?

FriendList.js var React = require('react'); var Friend = require('./friend.js'); var FriendList = React.createClass({ render: function() { return( <div> <h3& ...

Is it necessary to use both Vue Router and Express when incorporating Firebase into your project?

I am embarking on creating a simple application that will encompass various views, user authentication, data collection, database storage, and backend functionality to process and display the stored information. My chosen technology stack consists of Vue. ...

Exploring nested JSON data in Vue.js

In my attempt to access nested JSON within an array using Vue for a simple search functionality, I encountered a problem. Each school is encapsulated in a "hit" array, causing the system to perceive only one result of "hit" instead of returning data for ea ...

Maximizing efficiency in Office Automation programming by choosing individuals proficient in Javascript and PHP

I am seeking a solution where upon selecting a department checkbox, the employees belonging to that department will be displayed in the second div. This way, I can easily select an employee and have their information displayed in a separate section. I al ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...

Encountering the error message "The getStaticPaths function in Next.js requires the 'id' parameter to be provided as a string"

Having an issue with the getStaticPaths function. Every time I attempt to create a dynamic display using a parameter, it gives me an error message: A required parameter (id) was not provided as a string in getStaticPaths for / movies / [id]. However, if ...

"Learn how to seamlessly submit a form without reloading the page and send data back to the same page using Node and Express

I've already reviewed a few questions on this platform. They all focus on submitting post requests, but I believe the process should be similar for get requests as well. Therefore, I made modifications to my code to accommodate get requests. However, ...

Looking to transfer the name of the clicked link to a modal in order to execute a PHP/SQL query within the modal window

I am currently utilizing Twitter Bootstrap's modal feature. Within my table, I am mapping MAC addresses to vendor names using the following code: <tbody> <?php foreach ($rowarr as $k => $v) { ?> & ...

Activating a tab using a JS call in Bootstrap with the data-toggle attribute

My JSP page is using bootstrap's data-toggle="tab" functionality to display tabs. When the page loads, one tab is made active by default. <ul class="nav st-nav-tabs"> <li class="active"><a href="#tab1" data-toggle="tab">First Ta ...

Angular directive specifically meant for the parent element

I am working on a directive that I need to apply to a specific div element without affecting its child elements. The goal is to make the main div draggable, so that when it moves, its child divs move along with it. However, I do not want the child divs to ...

Is there an HTML5 input option specifically for timecodes?

Looking to implement an HTML5 input field for editing video and audio timecode, but struggling to find a suitable solution. The goal is to display and edit the following time components: Hours, minutes, seconds, and milliseconds. After researching, the ...

Error: Attempting to access properties of an undefined object (specifically, the 'prototype' property) within a React application

I encountered an error while working on my React application: TypeError: Cannot read properties of undefined (reading 'prototype') (anonymous function) C:/Users/tatup/Desktop/GrowApp/frontend/node_modules/express/lib/response.js:42 39 | * @pub ...

Seeking a solution for inserting input values into a JSON file within a node.js environment

As I was developing my new project, a to-do list web application, Below is the code snippet from 'todo.html' : <html> <head> <title>My TODO List</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Tips for creating a column with add, edit, and delete buttons in PHP

I found this code on a website that handles pagination and search functionality. However, I am looking to enhance it by adding an icon or button in a column that will allow users to link to the edit and delete functions for specific data selected in the ta ...

What's Next? Redirecting Pages in Node.js Express after Handling POST Requests

Is it possible to redirect to a different page from a post request? module.exports = function(app) { app.post('/createStation', function(request, response){ response.redirect('/'); //I'm having trouble getting ...

JavaScript opacity adjustments not achieving desired outcome

My attempt to make this sub menu fade in and out upon button press is not working as expected. It should fully fade in shortly after clicking 'help' and completely fade out when clicking 'back'. Is the problem with the method I'm u ...