Prevent duplicate entries in a JavaScript key-value data structure

Seeking advice from a novice.

I am working on a project where I need to create a list with a Key/Value structure. I have assigned the Id as the Key and the rest of the information as the value, so as I add more records, they get appended to my list $scope.itemList[]

var data = [
              {
                id: 1,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }, {
                id: 2,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }
            ];

            $scope.itemList = [];
            angular.forEach(data, function(item){
                var obj = {};
                var valObj = {};

                valObj.name = item.name;
                valObj.lastname = item.lastname;
                valObj.age = item.age;

                obj[item.id] = valObj;
                $scope.itemList.push(obj);
            });

The challenge I am facing is handling duplicate records in the JSON file. The current code does not check for duplicate ids while pushing items to the list. I have tried various methods to compare the object with the item's id but none seem to be working.

I would greatly appreciate any assistance or guidance on how to address this issue.

Answer №1

To achieve the desired outcome, consider converting the itemList from a list to a dictionary. You can modify the structure like this:

var data = [
              {
                id: 1,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }, {
                id: 2,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }
            ];

            $scope.itemDictionary = {};
            angular.forEach(data, function(item){
                var obj = {};
                var valObj = {};

                valObj.name = item.name;
                valObj.lastname = item.lastname;
                valObj.age = item.age;

                obj[item.id] = valObj;
                if(!$scope.itemDictionary[item.id]){
                     $scope.itemDictionary[item.id] = obj;
                }
            });

Answer №2

Solution

var dataset = [
  {
    id: 1,
    name : "John1",
    lastname : "Doe",
    age : 30
  }, {
    id: 2,
    name : "John2",
    lastname : "Doe",
    age : 32
  }, {
    id: 3,
    name : "John3",
    lastname : "Doe",
    age : 35
  }
];

$scope.itemList = [];
angular.forEach(dataset, function(entry){
  var newObj = {};
  var valueObj = {};

  valueObj.name = entry.name;
  valueObj.lastname = entry.lastname;
  valueObj.age = entry.age;

  if ( !newObj[entry.id]) {
    newObj[entry.id] = valueObj;
    $scope.itemList.push(newObj);
  }

});

However, if there is no compelling reason for newObj[entry.id], you may consider using findIndex from lodash or a similar method.

I cannot see why you would need two separate objects in this case.

update

var dataset = [
  {
    id: 1,
    name : "John1",
    lastname : "Doe",
    age : 30
  }, {
    id: 2,
    name : "John2",
    lastname : "Doe",
    age : 32
  }, {
    id: 3,
    name : "John3",
    lastname : "Doe",
    age : 35
  }
];

$scope.itemsList = [];
angular.forEach(dataset, function(item){
  if(_.findIndex($scope.itemsList, function(listItem){ return item.id === listItem.id }) === -1){
    $scope.itemsList.push(item);
  }
});

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

Updating a dataview inside a Panel in extjs 3.4

I am facing an issue with my extjs Panel component that includes a dataview item. Initially, it works perfectly fine in displaying images from a store. However, upon reloading the imgStore with new image URLs (triggered by a user search for a different cit ...

Looking for jQuery bbq... is the grill fired up yet?

In my exploration of the jQuery bbq plugin, I noticed that there is no reference to document.hash in the code. I believe that the function for retrieving the hash is located at line 1094: function get_fragment( url ) { url = url || location.href; ...

In what way can you reach an unfamiliar form within a controller?

I am working with multiple dynamically generated forms, each associated with a different model. In my controller, I need to iterate through all the errors within the forms. I assign form names based on the models. <form name="{{myForm}}" novalidate> ...

Utilizing webpack for server-side development

I'm currently in the process of creating a node back-end service using express and I was thinking about incorporating webpack to bundle everything into a single file (although I'm not sure if this approach is correct as I'm still learning). ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

Streaming audio live using HTML5 and NodeJS technology

I'm currently working on developing a website that functions as a VoIP recording application. The main goal is to capture audio from the microphone, send it exclusively to the server for storage and then have the server distribute the audio to connect ...

I am uncertain about the current status of this project; it functions correctly on my local machine but is encountering issues when deployed on the server

I'm facing an issue while transferring a project from local to server. The project works fine locally but not on the server, specifically when I try to edit products. The database is not displaying the correct information, as it shows two crucial numb ...

Choosing multiple images using JavaScript/jQuery

Gridster is being used for a webpage, with widgets containing images that can be added and deleted using the "+" and "X" buttons. Current Status Clicking the "+" button opens a modal where multiple images can be selected and added to the widgets by click ...

What is the best way to serialize a form with input files?

I'm facing a challenge with serializing and sending AJAX data from a form that includes a textarea and an input field for file uploads: <input type="file" name="files" file-input="files" multiple /> Can you help me with the correct way to ach ...

Send arguments to gulp task using the ionic serve command

I have mastered the art of seamlessly transitioning between production and development environments within an Ionic project. My guidance throughout this process has been the comprehensive tutorial found at Environment Variables in Ionic and AngularJS. The ...

Is it feasible for a JavaScript function to receive the innerHTML of the element from which it is invoked as an argument?

Is there a way to bind a function that takes a String as a parameter to a button so that it is called onclick and takes the innerHTML of the element as a parameter, without assigning the button an id or using queryselector? <button onclick="myFunct ...

Unable to locate the variable named StyleSheet

I've been delving into React Native using this informative site https://www.tutorialspoint.com/react_native/react_native_animations.htm However, I encountered a setback when attempting to launch the app on my iPhone. An error message indicates that a ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

Hide the menu when it is clicked in a React component

My objective: Implementing a functionality to close the Navbar by clicking the button placed within it. Despite my efforts, I am unable to make it work. I would appreciate any guidance on what I might be missing! Below is the code for my Navbar: import R ...

Exploring the process of linking multiple checkbox fields in a form with an ajax request

I have attempted the following method, but it is not working. I am able to retrieve the name from the form, but nothing gets assigned to the "sharewith" variable. My goal is to assign all selected checkboxes to one id called "sharewith" and then send them ...

Customize the background color of highlighted text using HTML and jQuery

Recently, I modified an existing code to divide plain text into four classes by selecting a portion of the text and coloring it. Afterwards, I extracted the text of each class and stored it in my database. While this code works well, I am looking for a way ...

What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully ...

When I try running my JavaScript code in the console, it works perfectly fine. However, I encounter an error when I attempt

Recently, I added a cool JavaScript code to my website that changes the background of the landing page randomly. Here is the snippet: var bgImages = [ "url('assets/bg/front1.jpg')", "url('assets/bg/fro ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...