save the data in localstorage with JSON - javascript

I made some test code, but it doesn't work what I want.
I push the data on localstorage, and get the data from localstorage. After that, I changed the value of data, and push and add the data on localsorage. Then, I checked the data and I was trying to get data with JSON.parse function. However, it didn't work.
Here's a code
var temp1 = {
'temp1': true,
'test1': true
};
var temp2 = {
'temp2': true,
'test2': true
};
var temp3 = [];
temp3.push(temp1);
localStorage.setItem("testing", JSON.stringify(temp3));
var temp4 = localStorage.getItem("testing");
var temp5 = JSON.parse(temp4);
for(var i=0; i<temp5.length; i++)
{
temp5[i].temp1 = false;
}
temp3.push(temp5);
localStorage.setItem("testing", JSON.stringify(temp3));
var temp6 = localStorage.getItem("testing"));
var temp7 = JSON.parse(temp6);
for(var j=0; j<temp7.length; i++)
{
temp7[i].test1 = false;
}
temp3.push(temp7);
localStorage.setItem("testing", JSON.stringify(temp3));

There are a couple of minor syntax errors as mentioed by si2zle, however the main issue is that when you are pushing temp5 and temp7 to temp3, you are actually pushing a new array instead of the individual elements.
You need to push each individual element to temp3 inside the for loop like so
for(var i=0; i<temp5.length; i++)
{
temp5[i].temp1 = false;
temp3.push(temp5[i]);
}

There was an error in the following code:
for(var j=0; j<temp7.length; i++)
{
temp7[i].test1 = false;
}
it was j++ not i++ and temp7[j].test1 = false; not temp7[i]

There is an extra ')' at var temp6 = localStorage.getItem("testing"));
also, while "temp3.push(temp5);" it pushes array in an array
like this: [{"temp1":true,"test1":true},[{"temp1":false,"test1":true}]]
which creates problem while parsing in the for loop.
for(var j=0; j<temp7.length; i++)
{
temp7[i].test1 = false;
}
Hope this helps:)

Related

Having Trouble Parsing Results of Array

I'm having a bit of trouble trying to parse the results of an array and print to the console. It's a two part problem actually. When I build the array it's adding "undefined" to the results. When I try to loop through the individual strings in the array it isn't parsing, just returning the full array object.
What I'm trying to do is collect all the field values selected from a list view and write them to another child list as separate items. When displaying results in a console it shows as an object array. When I run the typeof method against it I believe it shows as a string.
To reiterate, why am I getting undefined and why is my array not printing to console correctly. Below is an example of what is being returned thus far (when two records are selected) and my code.
Results:
undefinedDaffy DuckBugs Bunny
undefined
Code:
// Grabs selected items from getSelected function and passes parameters to writeSelected function
function callAccepted() {
getSelected().done(function(varObjects) {
for (var k in varObjects) {
console.log(varObjects[k]);
}
}); // End getSelected
} // End callAccepted
// Grabs selected items, accepts input from callAccepted or callRejected functions
function getSelected() {
var dfd = $.Deferred(function(){
var ctx = SP.ClientContext.get_current();
var clientContext = new SP.ClientContext();
var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
var items = [];
var arrItems = [];
for (var i in SelectedItems) {
var id = SelectedItems[i].id;
var item = targetList.getItemById(id);
clientContext.load(item, "Title");
items.push(item);
} // End for
clientContext.executeQueryAsync(
function(){ // Return to button click function
var itemLength = 0;
var itemObjects = [];
for (var j = 0; j < items.length; j++) {
itemObjects = items[j].get_item("Title");
itemLength += itemObjects;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
},
function(){ // Return to button click function
dfd.reject(args.get_message());
}
); // End ClientContext
}); // End dfd
return dfd.promise();
} // End getSelected
Why are you writing "var itemObjects;" in 1 line and add one string "itemObjects += items[j].get_item("Title");" in another? There'll be only 1 string anyway, so when you change those 2 lines into one, "undefined" should disappear:
function callAccepted() {
getSelected().done(function(varObjects, iLength) {
// Stuff
for (var k = 0; k < iLength; k++) {
console.log(varObjects[k]);
}
}); // End getSelected
} // End callAccepted
// Get user information function
function getSelected() {
var dfd = $.Deferred(function(){
var ctx = SP.ClientContext.get_current();
var clientContext = new SP.ClientContext();
var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
var items = [];
var arrItems = [];
for (var i in SelectedItems) {
var id = SelectedItems[i].id;
var item = targetList.getItemById(id);
clientContext.load(item, "Title");
items.push(item);
} // End for
clientContext.executeQueryAsync(
function(){ // Return to button click function
for (var j = 0; j < items.length; j++) {
var itemObjects = items[j].get_item("Title");
var itemLength = items.length;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
},
function(){ // Return to button click function
dfd.reject(args.get_message());
}
); // End ClientContext
}); // End dfd
return dfd.promise();
} // End getSelected
The reason for this is that after creating the variable without any value, it's undefined, so += 'Unicorn' will give us ugly 'UndefinedUnicorn'. If you wish to make variable for this purpose, write it "var x = ''".
And if - for example - you want to sum length of all "items", then this one function should look like:
function(){ // Return to button click function
var itemLength = 0;
for (var j = 0; j < items.length; j++) {
var itemObjects = items[j].get_item("Title");
itemLength += itemObjects;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
}
But I'm not exactly sure what are you trying to get here.

Model value is not getting reflected when changing the checkbox values using angular.element(document.querySelector(id)).attr('checked', true);

I have a logic like i have four checkboxes which should behave as existed code. Logic is working. But i do check and uncheck using the syntax.
angular.element(document.querySelector('#c_'+j)).attr('checked', true);
angular.element(document.querySelector('#c_'+j)).attr('checked', false);
which is not reflected in the respective checkbox element's model value. As you can check the attached screen shot. First three box got checked but it shows 'true' for actual clicked element rest remains 'false'. I need the updated model values. Anyone can help on this !
Here is the working example https://plnkr.co/edit/zA5V9gc6jTpPq3pIuvC8?p=preview
You should operate on $scope inorder to achieve two-way binding.
So, your function will change to,
function rangeCal(arg, bool){
var tmparray= [];
var selectedcheckbox;
for(var propt in arraymatrix){
tmparray = arraymatrix[propt];
for(var i=0; i <= tmparray.length; i++){
if(month === tmparray[i]){
selectedcheckbox = propt;
var a = 'c_'+selectedcheckbox;
$scope[a]= true
var gap = arg.split('_')[1];
if(!bool){
for(var j=propt; j<= gap; j++){
var j = 'c_'+j;
$scope[j]= true
}
}else if(bool) {
for(var k=propt; k<= gap+1; k++){
if(k > gap){
var k = 'c_'+k;
$scope[k]= false
}
var j = 'c_'+j;
$scope[j]= true
}
}
}
}
}
HERE IS THE WORKING PLUNKER
You can replace
angular.element(document.querySelector('#c_'+j)).attr('checked', true);
with
var index = 'c_'+j;
$scope[index]= true
and same process to make it unchecked by putting false in place of true
Check this snippet, hope this is what you were looking for. It is working for both actions, checking and unchecking.
function rangeCal(arg, bool){
var tmparray= [];
var selectedcheckbox;
for(var propt in arraymatrix){
tmparray = arraymatrix[propt];
for(var i=0; i < tmparray.length; i++){
if(month === tmparray[i]){
selectedcheckbox = propt;
angular.element(document.querySelector('#c_'+selectedcheckbox)).attr('checked', true);
var gap = arg.split('_')[1];
if(!bool){
for(var j=propt; j<= gap; j++){
var cb_id = "c_"+j;
$scope[cb_id] = true;
// angular.element(document.querySelector('#c_'+j)).attr('checked', true);
}
}else if(bool) {
for(var k=4; k>= gap; k--){
var gap_id = "c_"+k;
$scope[gap_id] = false;
// angular.element(document.querySelector('#c_'+gap)).attr('checked', false);
}
}
}
}
}
setTimeout(function(){
console.log($scope);
}, 2000);
}

I'm adding only the last element to the JS array

Here is my code so far: I am trying to create a new JSON object called dataJSON using properties from the GAJSON object. However, when I try to iterate over the GAJSOn object, I get only its last element to be added to the array.
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":
"3","country":"Spain"},{"bounceRate":"6","country":"Romania"},
{"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},
{"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
Your push of the new object should be within the loop.
for(var i =0; i<GAJSON.data.length; i++) {
viewJSON.data.push({
bounceRate: GAJSON.data[i].bounceRate,
country: GAJSON.data[i].country
});
}
DEMO
You are overwriting values every time at dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
Try this code:
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":"3","country":"Spain"},{"bounceRate":"6","country":"Romania"}, {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"}, {"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON[i] = [];
dataJSON[i]["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON[i]["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
console.log(viewJSON);
DEMO

Get Unique values during Loop

I am looping through an array and getting the data that I need.
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
}
What I am trying to do at this point is only show unique data in the loop.
For example var transAccount could be in the array 5 times. I only one to display that in my table once. How can I go about accomplishing this ?
Final Array is constructed like so; just as an object:
finalArray.push({
transID: tmpTrans,
transAccount: tmpAccount,
amEmail: amEmail,
merchName: merchName,
amPhone: amPhone,
amName: amName
});
var allTransAccount = {};
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
if(allTransAccount[finalArray[i].transAccount]) {
var transAccount = '';
}
else {
allTransAccount[transAccount] = true;
}
}
var merhcData = {};
var amName = {};
// and so on
for (var i = 0; i < finalArray.length; i++) {
merchData[finalArray[i].merchName] = finalArray[i].merchName;
amName[finalArray[i].amName] = finalArray[i].amName;
// and so on
}
If you are sure, that data in merchName will never be equal amName or other field - you can use one data object instead of several (merchData, amName...)
What you want is likely a Set. (see zakas for ES6 implementation. To emulate this using javascript, you could use an object with the key as one of your properties (account would be a good bet, as aperl said) which you test before using your raw array.
var theSet={};
for (var i = 0; i < finalArray.length; i++) {
var transAccount = finalArray[i].transAccount;
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
if(!theSet[transAccount]){
//add to your table
theSet[transAccount]===true;
}
This will prevent entries of duplicate data.

jquery csv function, how to return a value?

I have the following code. I am able to call the function "titlename" and execute the StatList function to read the CSV file. However I am not able to return any value.From browsing online I found that this question might be related to Ajax, but I donot know Ajax. I want to return the "titles" variable in the following example.
function titlename(title_number)
{
jQuery.get('TitleName.csv', function StatList(data)
{
var titles = new Array();
var title_array = jQuery.csv(undefined, undefined, '\r\n')(data);
for (var i=0; i<title_number.length; i++){
for (var j = 1; j< title_array.length; j++)
{
var tmp_compare = title_array[j].slice(0,title_array[j].length-1);
if(tmp_compare.toString() == title_number[i]){
var title = title_array[j][(title_array[j].length-1)];
//console.log(title);
titles.push(title);
break;
}
}
}
return titles;
});
}
Since AJAX is asynchronous you cannot simply return the value from a call to titlename. What you could do to use the information once it arrives is call another function and pass in the data you wanted to fetch as an argument. You can either process the data on the spot or process it in the function that you run. For demonstrative purposes, I'll leave your code where it was.
Here's an example of a potential next step:
var handleTitleData = function(titles){
// Do whatever you want now that you have the titles
}
var titlename = function(title_number){
jQuery.get('TitleName.csv', function StatList(data){
var titles = new Array();
var title_array = jQuery.csv(undefined, undefined, '\r\n')(data);
for (var i=0; i<title_number.length; i++){
for (var j = 1; j< title_array.length; j++){
var tmp_compare = title_array[j].slice(0,title_array[j].length-1);
if(tmp_compare.toString() == title_number[i]){
var title = title_array[j][(title_array[j].length-1)];
titles.push(title);
break;
}
}
}
handleTitleData(titles);
});
}
As others have said, when you call an asynchronous function, JavaScript will continue its normal execution, without waiting for it to complete, thus it will return before titles is defined. In order to get the result of the asynchronous call, you can use a $.Deferred object:
function titlename(title_number) {
return jQuery.get('TitleName.csv').pipe(function (data) {
var titles = new Array();
var title_array = jQuery.csv(undefined, undefined, '\r\n')(data);
for (var i=0; i<title_number.length; i++) {
for (var j = 1; j< title_array.length; j++) {
var tmp_compare = title_array[j].slice(0,title_array[j].length-1);
if(tmp_compare.toString() == title_number[i]){
var title = title_array[j][(title_array[j].length-1)];
//console.log(title);
titles.push(title);
break;
}
}
}
return titles;
});
}
titlename([1,2,3]).done(function(titles) {
// do what you want with the returned titles
}).fail(function() {
// deal with a failure in getting the .csv
});

Categories

Resources