Extract the ID from the array, save it, and then delete it from the local storage

I am currently developing a mobile application using Angular, JavaScript, Ionic, and Cordova.

Within one of my functions, I make use of an array called existingEntries, which is stored as a variable.

categories: Array [276]
 [0...99]
   0: Object
     id: 288
     exclude: false   
   1: Object
     id: 320
     exclude: true 

This function iterates through all elements in the array to check if the 'exclude' value is set to true or false.

    var existingEntries = $scope.categoryList;
    if(existingEntries == null) existingEntries = [];
        for (var i = 0; i < existingEntries.length; i++) {
            if (existingEntries[i]['exclude'] == true) {
                $scope.addLocalExcludedCategories(i);
            } else if (existingEntries[i]['exclude'] == false) {
                $scope.removeLocalExcludedCategories(i);
            }                       
    }

After this process, other related functions (addLocal.. and remove Local...) are invoked to store the IDs locally. The addLocal.. function is shown below, but it seems to produce duplicates when executed repeatedly. I believe there's room for optimization in the code. I'm currently utilizing local storage for saving the array, but I'm open to exploring alternative solutions.

    $scope.addLocalExcludedCategories = function(catID) {
    console.log("addLocalExcludedCategories Called")
    //Add Item to Excluded Categories Variable
    var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));                            
    if(existingEntries == null) existingEntries = [];

    var entryId = catID;
    var entry = {
        'id': entryId,
    };
    existingEntries.push(entry);        

    window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
    $scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");      
}

Below is the remove function, which seems to be having issues identifying IDs with 'exclude' values set to false instead of true.

$scope.removeLocalExcludedCategories = function(catID) {    
console.log("removeLocalExcludedCategories Called")
    //Remove Item from Excluded Categories Variable
    var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
    if(existingEntries == null) existingEntries = [];

    for (var i = 0; i < existingEntries.length; i++) {
        if (existingEntries[i]['id'] == catID) {
            console.log(i);
            existingEntries.splice(i, 1);
        }
    }

    window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
    $scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
    console.log($scope.ExcludedCategories);
}

I hope this explanation is clear. Thank you in advance for any assistance!

Answer №1

Make sure to check for existing entries in the existingEntries Array before adding new ones to avoid duplicates. Consider this revised code...

$scope.addLocalExcludedCategories = function(catID) {
    console.log("addLocalExcludedCategories Called")
    //Add Item to Excluded Categories Variable
    var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories")) || [];

    var entryId = catID;
    var entry = {
        'id': entryId,
    };
    if(existingEntries.length > 0){
    existingEntries.forEach(function(currentEntry){
     if(currentEntry.id !== entry.id){
      existingEntries.push(entry); 
    }
    });       

Answer №2

After some troubleshooting and experimenting with an ng-if statement, I managed to solve the issue by storing the array locally and then parsing it when needed.

$scope.checkExcludedCategory = function(categoryId){
    var notFound = true;
    var categoryList = JSON.parse(localStorage.getItem("categoryListMem"));
    
    for (var i = 0; i < categoryList.length; i++) {
        if (categoryList[i]['id'] == categoryId) {
            notFound = false;
        }
    }
    return notFound;
} 

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

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

Place a list with scrolling and overflow features side by side

Having trouble getting my headers to scroll with overflow auto and white-space nowrap. Can't figure out why it's not working. I want to create hyperlinks within headers to link to specific parts of the website. I have the code for hyperlinking s ...

What could be causing my form to malfunction when attempting to submit data using Ajax and an external PHP script that is handling two string inputs?

Hello, I am facing an issue while trying to utilize Ajax to interact with a PHP file and submit both inputs (fullname and phonenumber). When I click the submit button, it simply refreshes the page without performing the desired action. Below is the code I ...

Would it be unwise to create a link to a database directly from the client?

If I want to connect my React app to Snowflake all client-side, are there any potential issues? This web app is not public-facing and can only be accessed by being part of our VPN network. I came across this Stack Overflow discussion about making API cal ...

Fill your HTML form effortlessly using data from Google Sheets

I am relatively new to this topic, but I'm seeking a solution to populate an Apps Script Web App HTML dropdown form with names directly from a Google Spreadsheet. At the moment, I've managed to retrieve an array of names from column A in my sprea ...

Is an Ajax powered loading feature used in transitions between pages?

I recently came across this interesting website: It appears that they have implemented a clever technique where new content is dynamically loaded using AJAX, giving the impression of seamless navigation. Additionally, they have succeeded in hiding the bro ...

Display a limited number of characters along with a button on the blog tag pages. Clicking on the button will reveal the complete text description

Hey, I am looking to replicate the way WooCommerce tags descriptions are displayed on my WordPress blog. I want it to show only a certain number of characters with a "show all" link, similar to how it appears on this site: I have found some code that work ...

How to break down nested arrays into multiple arrays in Swift 4?

Using JSON parsing in my news API development brought about significant improvements. Here's how the JSON data structure is organized: > { "status": "ok", "source": "associated-press", "sortBy": "top", -"articles": [ -{ "author": "CHRISTINA A. CA ...

Issues with jQuery compatibility when used alongside HTML and CSS

My coding tool is flagging errors in my JavaScript file, including: -'$' usage before definition. -Incorrect spacing between 'function' and '(' This is the content of my JS file: $(document).ready(function() { $(window).s ...

Swift - JSON decoding error: "Was supposed to decode an array of any type, but instead found a dictionary."

Hello there! I have a question here that's at the root of my learning journey. I'm delving into SwiftUI and currently experimenting with data fetching from an API to store it in an array. At the moment, I have two essential files in place: First ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

What is the best method for saving and accessing a user-entered date using session storage?

https://i.sstatic.net/I8t3k.png function saveDateOfBirth( dob ) { sessionStorage.dateOfBirth = dob; } function getDateOfBirth() { document.getElementById("confirm_dob").textContent = sessionStorage.dateOfBirth; } function pr ...

How do I ensure that a nested <button> in AngularJS does not submit the form it is contained in?

My current project involves a form in AngularJS used for inputting data into a movie database. The form includes a dropdown menu allowing users to select actors to add to the movie record they are creating. However, when the user clicks the button next t ...

Why can't I capture the text within this particular div using .text?

Trying to extract specific text from a website in Chrome's developer console. For example, here is the code snippet: <div class="someClass">This is some text!</div> Expected it to work with this command, but it returns 'undefined&a ...

What methods can be utilized to enhance the visual appeal of a threejs model

I'm currently working on enhancing the visual quality of my 3D models, aiming for smoother edges and more realistic shadows. To achieve this, I am experimenting with an OBJ file format. Here's the code snippet I'm using to load and display t ...

Issue with pagination not updating when a checkbox is clicked

My goal is to create a filter function, but I am encountering issues with pagination when filtering. Specifically, when I click on the "Mobile Phone" checkbox, it only displays one record on the first page, two records on the second page, and so forth. Add ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

Preserve the Redux state when transitioning from a popup to the main window

My authentication process involves using auth0 to authenticate users. After selecting a provider, a popup opens for the user to choose an account to sign in with. With the help of the Auth0 sdk, I am able to retrieve user information such as email and nam ...

Adjusting the dimensions of the canvas leads to a loss of sharpness

When I click to change the size of the graph for a better view of my data in the PDF, the canvas element becomes blurry and fuzzy. Even though I am using $('canvas').css("width","811"); to resize the canvas, it still results in a blurry graph. I ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...