Angular allows you to retrieve values from localStorage

I have been trying to solve this issue by looking at various examples, but haven't been able to figure it out. In my Ionic app, I have a contact form that allows users to contact a listing owner.

After the form submission, I want to store the ad id in local storage to prevent repetitive submissions. I need to store the ad id in a JSON array and then check if it already exists in the session storage before displaying the form.

Currently, I am storing the ad ids in an array, but I am struggling to loop through and check if an id already exists. I attempted to use angular forEach, but the results are coming in as an object.

// Parse any JSON previously stored in allEntries
var existingEntries = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
if(existingEntries == null) existingEntries = [];

var adId = {
"id":$scope.adId
};
// Save allEntries back to local storage
existingEntries.push(adId);
localStorage.setItem("store_owner_ad_contacts", JSON.stringify(existingEntries));

var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
angular.forEach(values, function(value, key) {

// ^ This is coming as an object how can I get the key value?

if(value == adId){
//form has been submitted before
}else{
// show formVar = true 

console.log(key + ': ' + value);
});

This is how my storage currently looks:

[{"id":"100033"},{"id":"100035"},{"id":"1000336"}]

I am struggling to retrieve the id value from the JSON array (e.g. 1000033). How can I do this?

Answer №1

When looping through your data, remember to access object properties using the dot notation or bracket notation: object.yourProperty or object[yourProperty]

var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));

values.forEach(values, function(item, i) {

   // Inside the loop, each item is an object like this: {id: "100033"}
   // To access the id property, simply use dot notation

   if (item.id === '100033') {
     // Perform actions here
   }

});

Answer №2

// This code snippet demonstrates how to access keys within a forEach loop.
var index = 0;
for(index in data) {
     // Access the key using the 'index' variable.
}

Answer №3

It seems that the issue at hand is not directly related to Angular itself (simply using it within an Angular framework isn't the issue). If you have an array of values and need to search for a specific item, you can utilize Array.prototype.find. If your data is in the form of a stringified array, make sure to parse it using JSON.parse.

When working with localStorage in an Angular application, it is advisable to use ngStorage as it provides functions for stringifying, parsing, and additional options.

var lsItems = [{"id":"100033"},{"id":"100035"},{"id":"1000336"}];

var item = lsItems.find(i => i.id === "100035");
console.log(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

Is there a way to personalize the appearance of a specific page title in my navigation menu?

I'm currently working on customizing the menu of my WordPress theme to display a different color for the active page name. Although my CSS code works well for all page names except the current one: .navbar-nav li a { font-family: georgia; fo ...

The AngularJS ng-repeat filter {visible: true} does not respond to changes in properties

var myApp = angular.module('myApp', ['infinite-scroll']); myApp.controller('DemoController', function($scope, $timeout, $rootElement) { $scope.$rootElement = $rootElement; $scope.$timeout= $timeout; $scope.init = ...

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

Can Javascript be used to identify the number of td elements in a table and specify column widths within the table tags?

Is there a way to automatically add the "col width" tag based on the number of td tags within a Table tag? For example, if there are 2 td's, then it should add 2 "col width", and if there are 3 then, 3 "col width", and so on. <!DOCTYPE html> &l ...

Accessing the return value from an ASP.NET web service in JavaScript outside of the callback function

I am facing an issue with my ASP.NET web service that returns a simple string value. I have successfully called this web service using JavaScript and the script manager. However, I am in need of accessing the return value directly from where I made the cal ...

Glistening: sending reactiveValues to conditionalPanel

Is it possible to pass a reactiveValues to the condition of a conditionalPanel? If so, what is the correct method? Below is my attempt in the UI.R file for the conditionalPanel: conditionalPanel(condition = "values.cond == 0", etc. I have defined values ...

Retrieve main page elements from an additional page called PageSlide

I have implemented the jquery PageSlide plugin as a menu feature on my website. The plugin opens a separate page on the side of the main page to function as a menu. However, I am facing a challenge in accessing the main page's elements from this side ...

Leveraging the useRef hook to adjust the CSS styling of a React component

Currently, I am working on changing the style of a react component by utilizing the useRef hook. So far, I have implemented the useRef hook to reference the specific component whose style I want to modify when clicking on two buttons. Despite my efforts, I ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

UI-Router - templateUrl: "Ensure the content is securely delivered via HTTPS"

I am currently using HTTPS for my website. I have a requirement to send a request for templateUrl, not to a static file, but to the router: /:lang/content/library/book/:bookId Below is the setup for my state: .state('book', { url: '/ ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Using Node.js, is there a way to divide an object's array property by 100 and then store each portion in individual files?

Looking to break down a large object into chunks of 100 and save each chunk in separate files using Node.js. However, struggling to figure out how to split an array with thousands of records into files of 100. Query: How can I divide an object's arr ...

Getting the start of a day for a specific date in JavaScript while considering the timezone

I'm having trouble determining the start of a day while factoring in timezones using javascript. Consider this example: var raw_time = new Date(this.created_at); var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms); // Th ...

Measuring Page Loading Status using Ajax

I'm still learning Ajax and JQuery, and I've been having a tough time putting this together. My goal is to use ajax navigation to load URLs and implement back and front navigations with popstate. The code below is functional, but I'm facing ...

Is it necessary to include my library dependencies in the devDependencies section if I am only planning to publish the library bundle?

When creating a bundle for a library, should the library dependencies be placed in devDependencies? I am developing an NPM library in TypeScript that relies on several dependencies, including React components. As part of the build process, we compile to J ...

Obtain a Compilation of Video Sources in an HTML5 Format

Hey there, I am using an HTML5 video. This is just an example <video width="320" id="video" height="240" controls> <source src="video.mp4" type="video/mp4"> <source src="video1.mp4" type="video/mp4"> <source src="movie.ogg" typ ...

Decoding various JSON arrays received through AJAX requests

After returning two objects as JSON through AJAX, I am facing an issue with accessing the values in these two lists. Previously, when I had only one list, I could parse it easily. data = serialize("json", vm_obj) data2 = serialize("json", user_networks_li ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

Mastering ReactJs: The Ultimate Guide to Updating State Properties

I've been attempting to change the isSelected property for a specific row in my state data, but am finding that it's not updating. Can someone please offer guidance on the most effective approach to achieve this? var selecte ...