How to make a loop to look like this:
$scope.items = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 9 },
{ id: 10 } ];
I imagine it's something like this:
var keyName, value; $scope.items =[
for (i=0; i< localStorage.length; i++){
keyName = localStorage.key(i);
value = localStorage.getItem(keyName);
'{ id: value },'
}
];
Please some help, thanks.
Try this:
var key, value;
$scope.items = [];
for (var i = 0; i < localStorage.length; i++){
key = localStorage.key(i);
value = +localStorage[key];
$scope.items[i] = {id: value};
}
The purpose of the +
before localStorage
is to force the type (i.e. having {id: 42}
instead of {id: "42"}
), use parseInt() if you're not sure that the value is a number.
This will create the object that you requested:
var keyName, value;
$scope = { items: [] };
for (i=0; i< localStorage.length; i++){
id = localStorage.key(i);
value = localStorage.getItem(id);
$scope.items.push({ id:value});
}
If you just want the contents of localStorage, why not just use JSON.stringify(localStorage)