Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name

Below is my concept along with some sample code for reference:

$(".clickCompare").click(function ({
      var id = $(this).attr('data-id');
      var name = $(this).attr('data-name');           

      var datas = [id , name];
      localStorage["datas"] = JSON.stringify(datas);
      var stored_datas = JSON.parse(localStorage["datas"]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" class="clickCompare btn btn-primary" data-id="1" data-name="Sample1">Compare</button>
<button type="button" class="clickCompare btn btn-primary" data-id="2" data-name="Sample2">Compare</button>
<button type="button" class="clickCompare btn btn-primary" data-id="3" data-name="Sample3">Compare</button>

The objective is to capture the data-id and data-name values into the 'datas' variable every time a button with the class 'clickCompare' is clicked. This allows for easy retrieval of these values when needed.

If the ID already exists in the storage, it will not overwrite the variable datas.

Answer №1

One potential solution is to store an array of objects (tuple) for the desired data. For example, you can define datas as follows:

let datas = [{id: 1, name: 'first'}, {id: 2, name: 'second'}];

By doing this, each click event can trigger the addition of a new item to the array. To achieve this functionality, you can implement a function like the one below:

$(".clickCompare").click(() =>{
    let id = $(this).attr('data-id');
    let name = $(this).attr('data-name');  
    let datas = [];

    if(localStorage.key('datas')){
        datas = JSON.parse(localStorage.getItem('datas'));
    }

    if(!datas.filter(x => x.id == id)){
        datas.push({id: id, name: name});
    }

    localStorage.setItem('datas', JSON.stringify(datas));
    console.log(localStorage.getItem('datas')); //to remvoe after testing
});

Answer №2

Implementing key-value pair usage instead of an array can enhance functionality -

$(".clickCompare").click(function() {
  var id = $(this).attr('data-id');
  var stored_datas = localStorage["datas"];
  if (!stored_datas) {
    stored_datas = "{}";
  }
  var datas = JSON.parse(stored_datas);
  var existingData = datas[id];
  if (existingData) {
    console.log(`The data for id ${id} already exists: ${existingData}`);
    return;
  }
  var name = $(this).attr('data-name');
  datas[id] = name;
  var json = JSON.stringify(datas);
  localStorage["datas"] = json;
  console.log(`Added new data for id ${id}: ${name}`);
  var stored_datas = JSON.parse(localStorage["datas"]);
  console.log(`Content in Local Storage: ${json}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" class="clickCompare btn btn-primary" data-id="1" data-name="Sample1">Compare</button>
<button type="button" class="clickCompare btn btn-primary" data-id="2" data-name="Sample2">Compare</button>
<button type="button" class="clickCompare btn btn-primary" data-id="3" data-name="Sample3">Compare</button>

To view the demo since stackoverflow restricts localStorage, access this link

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

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

Error: The build process for Next.js using the command `npm run build`

Currently attempting to construct my application with target: 'serverless' set in the next.config.js file (in order to deploy on AWS Lambda). Upon running npm run build, I am encountering the following output: Warning: Built-in CSS support is bei ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

The issue arises with loading data from the server due to lack of definition of Mongo

I am experiencing a console bug and need assistance. It seems that there is an issue with loading data from the server as I am getting an error stating "Mongo is not defined." C:\Users\Robert\Desktop\FINISH\node_modules\mongod ...

How can I remove a row from an MVC webgrid using an ajax call?

Within my MVC Razor view, I have a partial view containing webgrid data. My goal is to include an action link to delete a specific row of data. To accomplish this, I crafted the following JavaScript function: function delMeal(pid) { if (confirm("Do yo ...

Automatically updating numbers upon adding input with jquery for a dynamic user experience

To keep the numbers in correct order #1, #2, #3, #4.... simply add an input and then reorder after removing any of them. |add_input+| (button) #1 |new_input| |remove| (button) #2 |new_input| |remove| (button) #3 |new_input| |remove| (button) If you ...

Making numerous changes to a single field in mongoDB can result in the error message: "Attempting to edit the path 'X' will generate a conflict at 'X'."

Looking to streamline my update operation: private async handleModifiedCategoryImages(data: ModifiedFilesEventData) { this.categoryModel .findByIdAndUpdate(data.resourceId, { $pullAll: { images: data.removedFiles || [] } ...

What causes the low Performance score of a default NextJS Application with no content?

Just started experimenting with my initial Next.js project. Upon generating a new project using create-next-app, I decided to test its performance with the web application 'Lighthouse'. Surprisingly, although most other metrics scored above 90, ...

What is the method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Node.js Monitoring Statistics Displayed in Command Line Interface

Apologies if this question has been asked before. I have been looking for something similar to what I need, but haven't been able to find it anywhere. So, I thought I'd ask. I am working with a nodejs script using puppeteer and I want to view st ...

Changing pricing on pricing table with a click

Looking to implement a price changing button that functions similar to the one found at this LINK: If anyone knows of any JavaScript or other solution, please provide me with some guidance. Thank you in advance. ...

Modify the class's height by utilizing props

Using Vue 3 and Bootstrap 5, I have a props named number which should receive integers from 1 to 10. My goal is to incorporate the number in my CSS scrollbar class, but so far it's not working as expected. There are no error messages, it just doesn&a ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

Saving multiple selected boxes based on a process using jQuery, PHP, and Ajax

I am working with a form that includes multiple select boxes. <form id="form"> <?php for($i = 1; $i<=9; $i++) { ?> <input type="hidden" name="modelID" value="1"/> <div> Process <?php ec ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

Enabling communication between JavaScript and PHP and vice versa

I am currently working on developing a Firefox plug-in with the purpose of gathering all the domains from the links located on the current site and showcasing their respective IP addresses. In order to achieve this, I have written JavaScript code that incl ...