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

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

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.

save the data in localstorage with JSON

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

Using a global array between files

I'm currently writing a Sketch Plugin and I'm trying to store data inside an global array. In the copy.sketchscript the data is generated, and in paste.sketchscript I'm trying to retrieve the array data. However, when I log the variable, it returns empty. What can I do to update the array data properly so that every function can access it?
Here's my code.
library/common.js
var verticalRulers = new Array; // global?
function copyVertical(context) {
var doc = context.document
var target = [[doc currentPage] currentArtboard] || [doc currentPage]
var countVertical = [[target verticalRulerData] numberOfGuides]
for(var i=0; i < countVertical; i++) {
var thisRuler = [[target verticalRulerData] guideAtIndex:i]
verticalRulers.push(thisRuler);
}
}
function pasteVertical(context) {
var doc = context.document
var target = [[doc currentPage] currentArtboard] || [doc currentPage]
for(i = 0; i < verticalRulers.length; i++) {
var thisRuler = verticalRulers[i];
[[target verticalRulerData] addGuideWithValue: thisRuler]
}
}
copy.sketchscript
#import 'library/common.js'
function onRun(context) {
verticalRulers = copyVertical(context);
log(verticalRulers) // return right data from variable;
}
paste.sketchscript
#import 'library/common.js'
function onRun(context) {
pasteVertical(context);
log(verticalRulers); // returns an empty array
}

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.

Cannot set property '0' of 2D array

Can anyone tell me why I'm getting this error for the code below:
Uncaught TypeError: Cannot set property '0' of undefined
var vehicles = [];
$.get('../poll/index.php?data=vehicles', function(data) {
var rows = $(data).find('row').length;
for (var i = 0; i < rows; i++) {
vehicles[i][0] = $(data).find('row').eq(i).find('stage').text();
vehicles[i][1] = $(data).find('row').eq(i).find('direction').text();
vehicles[i][2] = $(data).find('row').eq(i).find('stageName').text();
vehicles[i][3] = $(data).find('row').eq(i).find('atco').text();
vehicles[i][4] = $(data).find('row').eq(i).find('service').text();
vehicles[i][5] = $(data).find('row').eq(i).find('journey').text();
vehicles[i][6] = $(data).find('row').eq(i).find('fleet').text();
vehicles[i][7] = $(data).find('row').eq(i).find('longitude').text();
vehicles[i][8] = $(data).find('row').eq(i).find('latitude').text();
vehicles[i][9] = $(data).find('row').eq(i).find('operator').text();
vehicles[i][10] = $(data).find('row').eq(i).find('position').text();
}
}, 'xml');
You need to define each child array, e.g.
var vehicles = []; // parent array;
vehicles[0] = []; // first child array;
so you would need:
for (var i = 0; i < rows; i++) {
var vehicles[i] = [];
... rest of code here ...
}
vehicles[i] has no value assigned to it.
Add a line:
vehicles[i] = [];
at the top of the loop.

Categories

Resources