0

I have a single pair key and value stored in a localStorage. I want to put all records stored there into array:

function fillRecordArray(){
    recordArr.splice(0,recordArr.length);
    for(var i in localStorage) 
    {
        var record = new Record(i,localStorage[i]);
        recordArr.push(record);
    }   
}

Which works perfectly fine until I stopped to use Chrome and tested it on Mozilla. In this case I besides the data I saved I also get 6 extra array elements with these values:

1
function key() { [native code] }
function getItem() { [native code] }
function setItem() { [native code] }
function removeItem() { [native code] }
function clear() { [native code] }

What can cause this problem and is there any way to avoid it, besides just stripping it out from an array?

Thank you in advance.

  • 1
    [Why is using “for…in” with array iteration a bad idea?](http://stackoverflow.com/q/500504/215552) – Heretic Monkey Nov 02 '16 at 16:53
  • Does this help? https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object –  Nov 02 '16 at 17:04

4 Answers4

0

Firefox is giving you a storage api object: https://developer.mozilla.org/en-US/docs/Web/API/Storage . This is by design so I don't think there's a way to avoid it.

If you want to remove the extra functions, you could try casting your value as a specific type.

What's interesting is Chrome also implements WebAPI. If Chrome is not returning these functions, then you might want to check how you are getting/accessing/passing 'record'. Something could be changing its type.

Vinny
  • 449
  • 3
  • 6
0

Use a for loop to iterate over the length of localStorage, not a for in loop.

for(var i=0; i<localStorage.length; i++){
    var record = new Record(i, localStorage.getItem(localStorage.key(i)));
    recordArr.push(record);
}

However, I would prefer to store the records under a single container in localStorage, instead of having them as root keys.

For example:

// store the array
localStorage.setItem('records', JSON.stringify(recordsArr);

// retrieve the array
var retrievedRecords = localStorage.getItem('records');
if(retrievedRecords){
    retrievedRecords = JSON.parse(retrievedRecords);
} else {
    retrievedRecords = [];
}
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

Use Object.keys(), Array.prototype.forEach()

var keys = Object.keys(localStorage);

keys.forEach(function(key) {
  // do stuff
  console.log(localStorage[key]);
  var record = new Record(key, localStorage[key]);
  recordArr.push(record);
})
guest271314
  • 1
  • 15
  • 104
  • 177
0

This should work in both browsers... "hasOwnProperty" separates your data from the functions

recordArr = [];
for(var i in localStorage)
{
  if ( localStorage.hasOwnProperty(i) )
  {
    recordArr.push(i);
  }
}