Arrays and Localstorage - javascript

I'm having a little problem here, i have an array like this:
function crearObjetos()
{
var palabraPeso = "peso";
var palabraFecha = "Fecha";
var localStorageKey000 = "objetosPesoFecha";
var contador = 0;
var pesoFecha = new Array(); //THE ARRAY
while(contador < 365)
{
var nuevoObjeto = new Object;
var fechaActual = new Date();
nuevoObjeto.peso = 0;
nuevoObjeto.fecha = fechaActual;
nuevoObjeto.id = contador;
pesoFecha[contador] = nuevoObjeto; //SAVE OBJECTs IN THE ARRAY
contador = contador +1;
}
if (Modernizr.localstorage)
{
localStorage.setItem(localStorageKey000, pesoFecha); //STORAGE THE ARRAY
}
}
The problem is that, when i try to load the array in local storage, i can't acces any data, all are "undefined" and i don't know why... Here is how i load the data from the array (in this case only the first objetc):
function damePrimerObjetoPesoFecha()
{
//LOAD THE ARRAY FROM LOCAL STORAGE
var localStorageKey000 = "objetosPesoFecha";
var arrayDeObjetos = localStorage.getItem(localStorageKey000);
//CHECK IN AN ALERT IF THE DATA IS OK
alert("El primero que devuelve"+arrayDeObjetos[0].id);
//RETURN THE FIRSTONE
return arrayDeObjetos[0];
}

An array can't be pushed into localStorage just like how it is. You have to use JSON.stringify on it. This line :
localStorage.setItem(localStorageKey000, pesoFecha);
must be changed to
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha));
Similarly, when you're retrieving it from localStorage, you must use JSON.parse on it to convert it back to JSON. This line :
var arrayDeObjetos = localStorage.getItem(localStorageKey000);
must be :
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
Now when you access the first data, you wont get undefined.
Another alternative to this would be jStorage plugin which is wrapper around localStorage. It will take all the parsing problems from you and do it by itself if you pass an array or object to it.
Hope this helps!

localStorage only stores data as string.
You can strinify your array into JSON and save that and then parse it back when you load it
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha)); //STORAGE THE ARRAY
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));

LocalStorage can store strings only. You also need to remember that JSON.stringify converts date objects to string, so when deserializing via JSON.parse you need to manually create date for each object from array based on that string.
Firstly:
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha));
and then
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
arrayDeObjetos.forEach(function(objecto){
objecto.fecha = new Date(objecto.fecha );
})

localstorage can only store strings.
If you want to store arrays & objects, you should convert them to JSON.
Here's a small helper:
var LS = {
set: function (key, val) {
return localStorage.setItem(key, JSON.stringify(val));
},
get: function (key) {
return JSON.parse( localStorage.getItem(key) );
}
};
Use it as follows:
// Store the array:
LS.set(localStorageKey000, pesoFecha);
// Retrieve the array:
var arrayDeObjetos = LS.get(localStorageKey000);
Here's the fiddle: http://jsfiddle.net/KkgXU/

Related

How to iterate through an array stored in Local Storage JavaScript?

In this application I am getting this information from users in an HTML form: var orderName, trackingNumber, price the user is updating these dynamically. Then I'm storing them in an array, converting it to json format, and keeping the orderName variable (which the user gave earlier) as the local storage key,
var myArray = [];
myArray.push(orderName, trackingNumber,price);
var JsonOrder = JSON.stringify(myArray );
localStorage.setItem(orderName,JsonOrder );
Now I want to display all the orders and their information. One page with all the orders listed, and the orderName should be a HYPERLINK that takes user to a page with information on just that order.
Here is what I'm doing to loop through the array:
var savedOrders = JSON.parse(localStorage.getItem('orderName'));
var orderName;
var trackingNumber;
var price;
for (var key in savedOrders ) {
orderName = savedOrders[key][0];
trackingNumber = savedOrders[key][1];
price = savedOrders[key][2];
}
This isn't working?
simply do
let JsonOrder = JSON.stringify( [orderName, trackingNumber, price] );
localStorage.setItem('someName',JsonOrder );
//---
let orderName, trackingNumber, price;
[orderName, trackingNumber, price] = JSON.parse(localStorage.getItem('someName'));
I found an answer here:
// Get the existing data
var existing = localStorage.getItem('myFavoriteSandwich');
// If no existing data, create an array
// Otherwise, convert the localStorage string to an array
existing = existing ? existing.split(',') : [];
// Add new data to localStorage Array
existing.push('tuna');
// Save back to localStorage
localStorage.setItem('myFavoriteSandwich', existing.toString());
from https://gomakethings.com/how-to-update-localstorage-with-vanilla-javascript/
I think there is a better way then to use split since what if the user enters a [] or , as their input?But so far this works just not a good method.

How to stock array with localStorage (Chrome Extension)?

I tried to stock an array in localStorage but then I read it was impossible. So I tried that:
array = {};
array.name = $('[name="name"]').val();
array.username = $('[name="username"]').val();
array.password = $('[name="password"]').val();
alert(localStorage['accounts']);
local = JSON.parse(localStorage['accounts']);
localu = local.push(array);
alert(JSON.stringify(localu));
In fact the scripts stops at the first alert which returns '[]' (I previously put that value to check the result).
Why isn't my script working?
JavaScript, {} is an Object. [] is an Array.
var array = [] and var array = new Array() do the same thing.
An array is an ordered container of stuff, each value has an index not a key.
An object is a named container of stuff, each "stuff" has a key.
Your array is definitely an object.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
alert(localStorage['accounts']);
// > undefined OR the value
local = JSON.parse(localStorage['accounts']);
// local contains a parsed version of localStorage['accounts']
localu = local.push(array);
// localu = 0 (push returns the length i think?)
alert(JSON.stringify(localu));
Try the following. I've not tested it, but might work.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
if (localStorage['accounts'] == undefined) { // fixed
// does the key exist? No so create something to get us started
localu = { accounts: [] };
} else {
// the key exists! lets parse it
localu = JSON.parse(localStorage['accounts']);
}
// add the new "data" to the list
localu.accounts.push(data);
// save the results (we have to stringify it)
localStorage['accounts'] = JSON.stringify(localu);

jquery saving data in array

I want to save and add on every click data to an array. I tried this
var data = [];
var save = [];
s=0;
i=0;
some called function(){
data[i++] = some result;
data[i++] = some other result;
}
$('#someelement').click(function(){
save[s++] = data;
console.log(save); // for debugging
i = 0;
data = '';
});
The first save works, but after that I just empty arrays added. Any pointers ?
It's because you're replacing the Array with a string.
data = '';
You should replace it with a new Array instead.
data = [];
Or reuse the data Array by adding a shallow copy of data to save, then clearing data.
save[s++] = data.slice();
data.length = i = 0;
This allows any other code that has a reference to data to retain its reference so that it is always viewing the data that is being updated.
You might want to try making a copy of the data array:
save[s++] = data.slice(0);
This way, whatever happens to data array wont affect the save array's items.
You can use this:
data[data.length] = <some value>;
If you're trying to add the current contents of data to a single element in save, use Array.push:
$('#someelement').click(function(){
save.push(data);
console.log(save); // for debugging
i = 0;
data = [];
});
...or if it's that you want the current values in data added to save, use Array.concat, resetting data back to an empty array:
$('#someelement').click(function(){
save = save.concat(data);
console.log(save); // for debugging
data = [];
});
You should use [] to create new array.
Here is working example:
<script>
var data = [];
var save = [];
s=0;
i=0;
function addRes(){
data[i++] = 'some result';
data[i++] = 'some other result';
}
$('#someelement').click(function(){
addRes();
save[s++] = data;
console.log(save); // for debugging
i = 0;
data = [];
});
</script>

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

storing data in javascript

I want to iterate through a database and store the information as an array or object.
I don't really care which as long as I can store and retrieve based on a key.
I need guidence on the syntax to use to create and store data in javascript
// create storageEntity as array or objects
storageEntity = {};
storageEntity = [];
// on each retreival from data base store data in "storageEntity"
// conceptually it should look like this:
storageEntity[recordIFromFile][recordType][dataType] = value
where:
recordIFromFile - is an numeric value from file
recordType - is a string from file
dataType - is a string from file
value - is a numeric value from the file
You want to use an object/dictionary, i.e.
var storageEntity = {};
If your ID is 99999, you'd need 99998 empty entries in an array, I guess this isn't what you want. Now if you want to store a piece of data:
var record = storageEntity[recordIFromFile];
if (record == undefined) {
record = {};
storageEntity[recordIFromFile] = record;
}
var byType = record[recordType];
if (byType == undefined) {
byType = {};
record[recordType] = byType;
}
byType[dataType] = value;
Why can't you just request a JSON from your server and work over that instead?

Categories

Resources