Detecting and removing any duplicate entries in an array, then continually updating and storing the modified array in localstorage using JavaScript

I'm facing an issue with the function I have for pushing data into an array and saving it in local storage. The problem is that the function adds the data to the array/local storage even if the same profileID already exists. I want a solution that checks if the same profileID exists, removes the old object from local storage/array, and then adds the new data. Essentially, I want to avoid duplicates of the same profileID being saved in local storage or the array. Additionally, I want to ensure that only the most recent object is saved for the same profileID, overriding any older data.

 
  PUSHData(){
    var myobj = {
      Button: this.isReadMore,
       Class: this.sampleElem.className,
      ProfiliD: this.id,

    };
   
    
    const saved = JSON.parse(localStorage.getItem('CollapseState'));
    if(saved != null){
      this.array.push(myobj);
      localStorage.setItem('CollapseState',JSON.stringify(this.array));
    }else{
      this.array.push(myobj);
      localStorage.setItem('CollapseState',JSON.stringify(this.array));

    }

This is the current content of localStorage:

0: {Button: true, Class: "ShowHide", ProfiliD: "115279"}
1: [{Button: true, Class: "ShowHide", ProfiliD: "115279"},…]
  0: {Button: true, Class: "ShowHide", ProfiliD: "115279"}
  1: [{Button: true, Class: "ShowHide", ProfiliD: "115192"}]

Any assistance would be greatly appreciated.

Answer №1

When CollapseState contains an array of objects in localStorage, you can take the following steps to meet this requirement :

  • First, check if the CollapseState array exists in localStorage (which you are already doing)

    const saved = JSON.parse(localStorage.getItem('CollapseState'));
    
  • Next, since saved will be an array, iterate through it to determine if ProfiliD exists. If it does, remove the object from the array.

    saved.forEach((o, index) => {
      if (o.ProfiliD === myobj.ProfiliD) {
        saved.splice(index, 1);
      }
    });
    
  • Then, add the newObj to the saved array.

    saved.push(newObj);
    
  • Finally, update the saved array in localStorage.

    localStorage.setItem('CollapseState',JSON.stringify(saved));
    

Answer №2

It's recommended to update the existing item in the array instead of pushing a new one when the same ProfiliD already exists in the localStorage:

updateData(){
    var newObj = {
      Button: this.isReadMore,
      Class: this.sampleElem.className,
      ProfiliD: this.id,
    };
    
    const savedData = JSON.parse(localStorage.getItem('CollapseState'));
    if(savedData != null){
      this.array[this.array.findIndex(x=>x.ProfiliD == newObj.ProfiliD)] = newObj;
      localStorage.setItem('CollapseState',JSON.stringify(this.array));
    }else{
      this.array.push(newObj);
      localStorage.setItem('CollapseState',JSON.stringify(this.array));
    }
}

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

Tips for setting a Bootstrap 3 dropdown menu to automatically open when located within a collapsed navbar

Is there a way to have my dropdown menu automatically open when the collapsed navbar is opened? Take a look at this example I created in a fiddle to see what I'm working with so far. Right now, when you click on the navbar in its collapsed state, two ...

The 'then' property is not found on the type 'CloudFunction<Change<DocumentSnapshot>>'

Encountered an error: The property 'then' does not exist on type 'CloudFunction>' in my Firebase cloud function. Does anyone have a solution? exports.rebuildFormTriggerClientDetails = functions.firestore. document('clientDeta ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

Struggling to Make Div Refresh with jQuery/JS in my Rails Application

I'm currently facing an issue in my Rails app where I am unable to refresh a specific Div element. The Div in question is located in bedsheet_lines_index.html.erb <div id="end_time_partial" class="end_time_partial"> <%= render :partial ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

Tips for giving a unique name to an array before including it in a collection of arrays in PHP

I am trying to figure out a way to name an array before adding it to a group of arrays. Below is the code that I have, which retrieves a list of files from a directory, reads the contents of each file, and adds them to an array. public function buildArray ...

Transforming a string into a proc using Ruby and Rails

Here's the scenario I'm dealing with. The current URL appears as follows: /categories/Art Using name = location.pathname.split('/')[2], I extract the Art part of the URL. Then, I send an AJAX request to the controller with the followi ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

MongoError: Transaction could not be initiated

I recently delved into using mongoose transactions for the first time. Following the guidelines in the documentation and some related articles, I managed to get it up and running with the help of run-rs for local replicas. However, I encountered a couple o ...

Iterating through a JSON query in AngularJS using the ng-repeat directive

Using AngularJS in my current project has been a smooth experience so far. One thing I have noticed is that when I loop over employees in my view, I have to use the code <li ng-repeat="employee in employees.employee"> instead of just <li ng-re ...

Mastering the alignment of Material-UI Menu items

When using the menu and menu item components of material-ui to create a select dropdown menu, I encountered an unusual issue where the dropdown menu always expands to the left side of the box, as shown in the image below: https://i.stack.imgur.com/ykRrp.jp ...

Seasonal selection tool

I need a quarterly date picker feature, ideally using Angular. I am interested in something similar to the example shown below: https://i.stack.imgur.com/9i0Cl.png It appears that neither Bootstrap nor (Angular) Material have this capability. Are there a ...

What are the best practices for managing data input effectively?

I am facing a challenge with input validation. I need to restrict the input to only accept strings of numbers ([0-9]) for the entity input field. If anything else is entered, I want to prevent it from overwriting the value and displaying incorrect input. I ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

Is it possible for a function parameter to utilize an array method?

Just starting to grasp ES6 and diving into my inaugural React App via an online course. Wanted to share a snag I hit along the way, along with a link to my git repository for any kind souls willing to lend a hand. This app is designed for book organization ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

Discover the process of linking a JavaScript file to an HTML file in React

I am trying to render a React JS file that contains the following code: React.render( <TreeNode node={tree} />, document.getElementById("tree") ); I have included this file in an HTML document like so: <!doctype html> <html lang=" ...

Increasing the concealment of items

My query is about creating an expandable tree structure while iterating through an array in AngularJS. I managed to make it work, but the issue is that all nodes expand and collapse together. Here's my HTML: [...] <div ng-repeat="item in items"&g ...