limit limit - 4 months ago 14
Javascript Question

localStorage get value using angular

I looked at some examples, but can't seem to figure this out. Basically I have a contact form in an ionic app that allows a user to contact a listing owner.

When they submit the form I want to store the ad id in local storage so they can't repeatability submit it over and over.

I need to be able to store json array and then check the results. If the ad id is in session storage don't show the form else show it.

I am currently doing this, which seems to store the ad ids in an array, but how do I loop through to check if an id exists? I tried angular forEach, but results come 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{
// showformVar = true

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


My storage looks like this

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


How do I get id value? (e.g 1000033)

Answer

In your loop you have an object, so just access id property like you do with an object: object.yourProperty or object[yourProperty]

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

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

     // you get object like this {id: "100033"}
     // so to access id do like normal object

     if (item.id === '100033') {
       // do something
     }

  });