jquery saving data in array - javascript

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>

Related

How to select specified data like id in a for loop to use those data in different page

I want to get and store id from idArray to use each id indvidual
I tried to store in session storage but it return the last element
success: function (data) {
const myText = "";
const addressArray = [];
const titleArray = [];
const typeArray = [];
const idArray = [];
data.map((user) => {
addressArray.push(user.address);
titleArray.push(user.title);
typeArray.push(user.jtype);
idArray.push(user.id);
});
container.innerHTML = "";
for (let i = 0; i <= 3; i++) {
let clone = row.cloneNode(true);
container.appendChild(clone);
container.firstChild.innerHTML = "";
jobtitle.innerHTML = data[i].title;
jbtype.innerHTML= typeArray[i];
jbaddress.innerHTML= addressArray[i];
sessionStorage.setItem('jobid',idArray[i]);
}
}
The issue I can see is , since the key is always same , it is overriding the value of the same key.
You can instead do something like
sessionStorage.setItem("jobid-"+i,idArray[i]);
This should solve the problem for sure.
It returns the last value because you are using the same key to store each value. Try using a different key for each or alternately, create an array of ids using map function and store the array in session with the key 'jobid'.
You can serialize and store it in session as follows:
sessionStorage.setItem('jobid', JSON.stringify(idArray));
To read the same back out you can use code like
JSON.parse(sessionStorage.getItem('jobid'));

How to dynamically add object to array (closure in loop)

I read couple posts about the closure in loop but still not really get it how to apply to my situation.
I have three feed urls defined in HTML and using JavaScript promise to return the response when it's ready without blocking the UI. I am able to get two blog entries data per feed url. Now, each returned blog entry has its published date and I would like to sort them from latest to oldest. However, I keep getting the last value when I pushed the object to array. I know this is something to do with closure and since I'm not familiar with closure, I have difficulty to solve this problem. Any help is great appreciated!
var itemArray = [];
var entryObj = {};
promise.then(function (response) {
var parser = new DOMParser();
xml = parser.parseFromString(response, "text/xml");
var items = xml.getElementsByTagName("item");
for (var x = 0; x < items.length && x < limits; x++) {
title = items[x].getElementsByTagName("title")[0].innerHTML;
link = items[x].getElementsByTagName("link")[0].innerHTML;
pubDate = items[x].getElementsByTagName("pubDate")[0].innerHTML;
creator = items[x].getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", "creator")[0].innerHTML;
entryObj.title = title;
entryObj.link = link;
entryObj.pubDate = pubDate;
entryObj.creator = creator;
itemArray.push(entryObj);
// output: all 6 objects contain last value
console.log(itemArray);
}
});
In short : Move the object creation inside the loop.
It's nothing to do with closure. The issue is, you are pushing the same object.
You need a new object to be pushed. So create the object inside the for loop. So that every time you get a new object and it gets pushed to the array.
Code-
var itemArray = [];
promise.then(function (response) {
var parser = new DOMParser();
xml = parser.parseFromString(response, "text/xml");
var items = xml.getElementsByTagName("item");
for (var x = 0; x < items.length && x < limits; x++) {
var entryObj = {};
title = items[x].getElementsByTagName("title")[0].innerHTML;
link = items[x].getElementsByTagName("link")[0].innerHTML;
pubDate = items[x].getElementsByTagName("pubDate")[0].innerHTML;
creator = items[x].getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", "creator")[0].innerHTML;
entryObj.title = title;
entryObj.link = link;
entryObj.pubDate = pubDate;
entryObj.creator = creator;
itemArray.push(entryObj);
// output: Now all values are unique
console.log(itemArray);
}
});
Move var entryObj = {}; into your for loop.

How to put data into multi dimensional array in js inside the loop

How can we put data into multi dimensional array or json within a loop.
I know that it's possible to store multi dimensional data at one time, but I want it inside the loop as I have described in the code.
var sub_cat_checked_val = [];
sub_cat_checked.each(function (index) {
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
sub_cat_checked_val['key_one']['key_two']='value';
sub_cat_checked_val[sub_cat_id][index] = index:jQuery(this).val();
});
As it's possible in php like $var_name['key1']['key2']['keyn']='value';
sub_cat_checked_val[sub_cat_id] needs to be defined as an array, so add the lines:
if (!sub_cat_checked_val[sub_cat_id]) {
sub_cat_checked_val[sub_cat_id] = [];
}
to define the value as an array if it does not exist.
Try this snippet:
<script>
var k = {};
k.a = {};
k.a.b = {};
k.a.b.c = {};
k.a.b.c.d = 5;
console.log(k);
</script>
I was able to do it with all of you guys help with some of modifications.
Here is what I did:
sub_cat_checked.each(function (index) {
console.log(index_val);
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
console.log(sub_cat_id);
if (sub_cat_checked_val[sub_cat_id] == undefined) {
sub_cat_checked_val[sub_cat_id] = [];
}
sub_cat_checked_val[sub_cat_id][index] = jQuery(this).val();
});
Thanks a lot to all of you.

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

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/

Categories

Resources