localStorage only saves first member of array - javascript

Every time I want to get the array from localStorage it only gets me the last value.I think it handles the array as a object. How do I fix this?
function saveData() {
if ($("#forma").valid() == true) {
var Name = document.getElementById("username").value;
var Year = document.getElementById("godinaupisa").value;
var Index1 = document.getElementById("brindeksa").value;
console.log(Name);
var EMial = document.getElementById("email").value;
var OBJ = { NAME: "JOHN DOE", YEAR: "18", INDEX1: "1", EMAIL: "#" };
OBJ.NAME = Ime1;
OBJ.YEAR = Year;
OBJ.INDEX1 = Index1;
OBJ.EMAIL = EMial;
var arrayOBJ = [];
arrayOBJ.push(OBJ);
localStorage.setItem("ARRAY", JSON.stringify(arrayOBJ));
alert("saved");
$("#forma").resetForm;
};
}

So, you're calling setItem which will just set it to whatever you pass it. I think what you want to go is read the current value, append to that and set the new value to be that.
var data = localStorage.getItem("ARRAY");
data = JSON.parse(data);
data.push(OBJ);
localStorage.setItem("ARRAY", data);

Because you create the arrayOBJ array each time you try to save, you're only ever going to have one item inside of it. And when you save it to localstorage you're just writing over anything that was already there. Instead try defining arrayOBJ outside your save function as a global variable.
Alternatively you can use localStorage.getItem and JSON.parse to get the current array that's in localStorage before pushing to it.

Related

Push values to array in jquery

I have List of items data and empty array quotations :
var data = {};
var quotations = [];
I want to fill quotations with data values ,Every time i add new data it added successfully but all data values get last value .
for example :
$("#addquotation").click(function () {
debugger;
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
for first time i add
"test,45,testnotes,2016-02-03" Second time i 've added
"test2,45.2,testnotes2,2016-02-05"
when i debug i get data as :
obj(0): "test2,45.2,testnotes2,2016-02-05"
obj(1):"test2,45.2,testnotes2,2016-02-05"
it seems it append last version to all data
Please Advice . Thanks
You need to declare data inside the click handler, if it's declared as a global variable you are basically always modifying and adding the same data object to the array:
var quotations = [];
$("#addquotation").click(function () {
debugger;
var data = {};
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
You are pushing the same object reference each time since you declared data outside of the click handler.
Change from :
var data={};
$("#addquotation").click(function () {
To
$("#addquotation").click(function () {
var data={};// declare local variable
The problem is that data is a global variable and you add a reference to data to quotations.
When the first value is pushed to quotations, data and quotations[0] refer to the same object. Here is an example of what is happening:
var a = {num: 1};
var b = a;
b.num = 2;
console.log(a.num); // prints 2
The same thing happens when an object is pushed to an array. quotations does not contain a copy of data, it contains a reference to data so that modifying data also modifies quotations. To fix this, each element of quotations must refer to a different data object. This can be accomplished by defining data inside of the function instead of outside.
Replace
var data = {};
$("#addquotation").click(function() {
// populate data, push to quotations
});
with
$("#addquotation").click(function() {
var data = {};
// populate data, push to quotations
});

How can i create object once we have values?

I am new to javascript so i dont know how to create object once we have values dynamically , so below code i have fullName and workerKey from dataItem now i want to create object selectedOwners with values of fullName and workerKey.
How can i achieve that task ?
ctrl.js
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
var fullName = dataItem.fullName;
var workerKey = dataItem.workerKey;
console.log('WORKER KEY', workerKey);
}
You use an object initializer:
selectedOwners = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
};
The object initializer is the {...} bit. Each of those two things inside it is a property initializer. The part before the : is the name, the part after is the value, which can be the result of any expression.
In your code, you'd already created the object (var selectedItem = {};). The code above will replace that object. If you just wanted to add to it, you'd just use assignment:
selectedItem.fullName = dataItem.fullName;
selectedItem.workerKey = dataItem.workerKey;
Which you use depends on whether it matters that you not create a new object.
Edited, as per comments:
var list = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwners = {"fullname":dataItem.fullName,"workerKey":dataItem.workerKey};
list.push(selectedOwners);
}
// use list to populate output
You have already created the object so all you need to do is add the values into it.
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
selectedOwners.fullName = dataItem.fullName;
selectedOwners.workerKey = dataItem.workerKey;
//This will print out the newly populated object
console.log(selectedOwners);
}

Arrays and Localstorage

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/

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);

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;

Categories

Resources