Javascript array push is not giving desired result - javascript

The problem I am having is when im pushing or unshifting items into array they are being automatically grouped, very strange:im guessing my loops are not well put together, more or less im experimenting.any help is appreciated.
var i;
var anObject:/*is created dynamically in a loop for instance I load random images
and push into ' myArray'. My myaArray should
look like this:["image1,image3,image2,image3,image2] but instead
im getting:["image1,image3,image3,image2,image2] there grouping up for some reason,
But i dont want them too*/
var BookH = [];
function create(){
for (var i=0; i<10; i++){
var object;
var tempObject;
var loader = new THREE.OBJMTLLoader();
loader.load( 'mod/'+mysqlVars[i].Format+'.obj','mod/bookH.mtl') ;
loader.addEventListener( 'load', function ( event ) {
object = event.content;
for(k in object.children){
object.children[k].castShadow = true;
object.children[k].receiveShadow = false;
}
tempObject = object.clone();
BookH.push(tempObject);
console.log('mod/'+mysqlVars[9].Format);
if(BookH.length == 10){
populate();
}
});
}
/////////counter loop///
}

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

How can I put JSON data into a jQuery/Javascript array for later use?

I have some code like this:
var data = // coming in from AJAX and confirmed working, don't need to wory about this...
var row = // cloning an existing HTML structure in the DOM
for (i = 0; i < data.length; i++) {
var rowclone = row.clone();
var orderLastChangedTime = new Date(data[i].createDate);
var diffDays = Math.round(Math.abs((currentTime.getTime() - orderLastChangedTime.getTime())/(oneDay)));
rowclone.find(".home-order-calc").text(diffDays);
rowclone.find(".home-order-status").text(data[i].status);
rowclone.find(".home-order-po-number").text(data[i].poNumber);
rowclone.find(".home-order-number").text(data[i].orderId);
rowclone.find(".home-order-last-changed").text(orderLastChangedTime);
rowclone.find(".home-order-lines").text(data[i].itemsCount);
rowclone.find(".home-order-cost").text(data[i].cost);
var rowstatus = rowclone.find(".home-order-status").text();
rowstatus = rowstatus.toUpperCase();
openJSONitems = [];
closedJSONitems = [];
otherJSONitems = [];
if (status[rowstatus] == "open") {
openJSONitems.push(rowclone);
}
else if (status[rowstatus] == "closed") {
closedJSONitems.push(rowclone);
}
else {
otherJSONitems.push(rowclone);
}
console.log(openJSONitems);
openJSONitems.appendTo("#home-table-orders");
}
I am trying to create 3 new JavaScript arrays and array push data into them based on sort criteria from the JSON payload. Once they are sorted I want to hang on to them and attach them to the DOM on some user actions... what am I doing wrong?
openJSONitems is an array, it doesn't have the appendTo method, you'll have to iterate over that array and append its elements to "#home-table-orders". Besides, you're creating a new array in each iteration. I think this changes would fix the problem. You could also avoid the last loop inserting the element directly when status[rowstatus] == "open" if you liked.
var openJSONitems = [],
closedJSONitems = [],
otherJSONitems = [];
var data = // coming in from AJAX and confirmed working, don't need to wory about this...
var row = // cloning an existing HTML structure in the DOM
for (i = 0; i < data.length; i++) {
var rowclone = row.clone();
var orderLastChangedTime = new Date(data[i].createDate);
var diffDays = Math.round(Math.abs((currentTime.getTime() - orderLastChangedTime.getTime())/(oneDay)));
rowclone.find(".home-order-calc").text(diffDays);
rowclone.find(".home-order-status").text(data[i].status);
rowclone.find(".home-order-po-number").text(data[i].poNumber);
rowclone.find(".home-order-number").text(data[i].orderId);
rowclone.find(".home-order-last-changed").text(orderLastChangedTime);
rowclone.find(".home-order-lines").text(data[i].itemsCount);
rowclone.find(".home-order-cost").text(data[i].cost);
var rowstatus = rowclone.find(".home-order-status").text();
rowstatus = rowstatus.toUpperCase();
if (status[rowstatus] == "open") {
openJSONitems.push(rowclone);
}
else if (status[rowstatus] == "closed") {
closedJSONitems.push(rowclone);
}
else {
otherJSONitems.push(rowclone);
}
}
console.log(openJSONitems);
for (i = 0; i < openJSONitems.length; i++) {
$(openJSONitems[i]).appendTo("#home-table-orders");
}
You could add then as a data element onto a DOM object.
$('body').data('openItems', openJSONitems);
And retrieve them later:
var items = $('body').data('openItems');
Have you considered using localStorage?
localStorage.setItem('openJSONitems', openJSONitems );
And retrieving it with...
var openJSONitems = localStorage.getItem('openJSONitems');

create unique nested objects dynamically

I need to create unique objects(Route) for the my variable's routes property. And this has to be done in a loop.
Please check out my code blow or http://jsfiddle.net/2gk36mvo/ to have a more clear image about my problem.
html
<input type="button" value="ss" onclick="initialize();">
javascript
var my={
routes:{}
};
function Route(points)
{
this.points = points;
return this;
};
function getRoutes(routes){
var result = [];
for (var prop in my.routes) {
result.push(prop);
}
return result.toString();
}
function initialize()
{
// create and add objects manually
my.routes.r0 = new Route("blabla0");
my.routes.r1 = new Route("blabla1");
alert(getRoutes(my.routes)); // gives 'r0,r1'
// clear the routes for the dynamic test
my.routes = {};
// create and add objects dynamically
for (i = 0; i < 2; i++) {
//???????????? create and and add the new Route objects
}
alert(getRoutes(my.routes)); // must give the same result as above 'r0,r1'
}
As cackharot states in his comment, you need to have code similar to this in your for loop:
for (i = 0; i < 2; i++)
{
my.routes["r"+i] = new Route("blahbla"+i);
console.log(my.routes);
}

Getting value of "i" from GEvent

I'm trying to add an event listener to each icon on the map when it's pressed. I'm storing the information in the database and the value that I'm wanting to retrive is "i" however when I output "i", I get it's last value which is 5 (there are 6 objects being drawn onto the map)
Below is the code, what would be the best way to get the value of i, and not the object itself.
var drawLotLoc = function(id) {
var lotLoc = new GIcon(G_DEFAULT_ICON); // create icon object
lotLoc.image = url+"images/markers/lotLocation.gif"; // set the icon image
lotLoc.shadow = ""; // no shadow
lotLoc.iconSize = new GSize(24, 24); // set the size
var markerOptions = { icon: lotLoc };
$.post(opts.postScript, {action: 'drawlotLoc', id: id}, function(data) {
var markers = new Array();
// lotLoc[x].description
// lotLoc[x].lat
// lotLoc[x].lng
// lotLoc[x].nighbourhood
// lotLoc[x].lot
var lotLoc = $.evalJSON(data);
for(var i=0; i<lotLoc.length; i++) {
var spLat = parseFloat(lotLoc[i].lat);
var spLng = parseFloat(lotLoc[i].lng);
var latlng = new GLatLng(spLat, spLng)
markers[i] = new GMarker(latlng, markerOptions);
myMap.addOverlay(markers[i]);
GEvent.addListener(markers[i], "click", function() {
console.log(i); // returning 5 in all cases.
// I _need_ this to be unique to the object being clicked.
console.log(this);
});
}
});
You have an issue with closures. Your functions see i's last valuse. Simply add another closure to fix your error:
for(var i=0; i<lotLoc.length; i++) {
(function(i){
// ...
})(i); //run the function with i as argument
}//for

Categories

Resources