limit
limit

Reputation: 647

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)

Upvotes: 5

Views: 46544

Answers (3)

Gatsbill
Gatsbill

Reputation: 1790

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
   }

});

Upvotes: 4

Morteza Tourani
Morteza Tourani

Reputation: 3536

As I see this is not about not about angular itself (using this in an angular doesn't mean relation). If you have an array of values and want to search for something then you can use Array.prototype.find. if your data is stringified array then you should parse it before with JSON.parse.

If you're about to use localStorage in your angular app then that would be better to use ngStorage which handles stringify and parse and some more options.

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

var item = lsItems.find(i => i.id === "100035");
console.log(item)

Upvotes: 1

Sasank Sunkavalli
Sasank Sunkavalli

Reputation: 3964

// inside forEach loop
var k = 0;
for(k in value) {
     // u can get the key in this way (k) 
}

Upvotes: 1

Related Questions