How to fetch or convert Parse query into array (JavaScript SDK) - javascript

I have a column in my Parse database populated with numbers and I'm trying to add them all together to get a total.
I know how to do the adding together if the data returned is a single array, but I can only figure out how to return the numbers as individual objects. This is my code which does that:
var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
console.log(object.get('costMonthly'));
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
How would I go about fetching what I want as an array or at least converting what I have into one?

It looks like you are trying to sum the costMonthly field. You can use reduce to do this easily:
var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
success: function (results) {
var sum = results.reduce(function(prev, cur) {
return prev + cur.get('costMonthly');
}, 0);
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
If your goal is an array of the costMonthly values, this will work:
var monthlyCosts = results.map(function(item) {
return item.get('costMonthly');
});
Read more about reduce here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

You can create a temporary array , and push results though through iteration , not the best solution , but is very useful if you want to manipulate results later :
var costMonthlyArray=[];
var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var cost=object.get('costMonthly');
costMonthlyArray.push(cost);
console.log(cost);
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});

Related

Get Geopoints from parse.com javascript

I have succesfuly stored some geopoints in Parse.com and now in another page i want to console log them all so i can place them into some variables and then put one marker in google map.
So i'm trying with this code to get them but for sure i miss some thing and i need your advice.
Parse.initialize("APPID", "JSKEY");
var PhotoObject = Parse.Object.extend('magazia');
var photoObject = new PhotoObject();
var query = new Parse.Query(PhotoObject);
query.select('latlon');
query.find({
success: function(locationList) {
alert("Successfully retrieved " + locationList.length + " locations.");
for (var i = 0; i < locationList.length; i++) {
var locationsBlock = {};
locationsBlock = JSON.parse(JSON.stringify(locationList[i]));
var location = {};
location = JSON.parse(JSON.stringify(locationsBlock.geolocation));
alert(location.latitude);
};
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
So i have a class called "magazia"
and inside that class there is a column which is called "latlon" and its a Geopoint. The content of this column is for example 48.29124, 28.52015 float number.
The alert shows me the correct number of rows that there are in the "magazia" class.
Does anyone knows why i dont get the results from my code above?
thanks in advance.
Ok that was a stupid mistake
var PhotoObject = Parse.Object.extend('magazia');
var photoObject = new PhotoObject();
var query = new Parse.Query(PhotoObject);
query.select('latlon');
query.find({
success: function(locationList) {
console.log("Successfully retrieved " + locationList.length + " locations.");
for (var i = 0; i < locationList.length; i++) {
var locationsBlock = {};
locationsBlock = JSON.parse(JSON.stringify(locationList[1]));
var location = {};
location = JSON.parse(JSON.stringify(locationsBlock.latlon));
var lat = location.latitude;
var lon = location.longitude;
console.log(lat, lon);
};
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
instead of locationsBlock.geolocation
there should be locationsBlock.latlon

How to access HTML input element on javascript

I'm trying to retrieve the customers name by alert based on the account number that's entered into the textbox by i'm having trouble referencing the textbox (>>txtFree<<). I just not sure what i must replace it with if anyone could help please.
HTML
Account Number: <input type="text" id="txtFreeBank" name="txtFreeBank" />
JS
function checkBankAc() {
var txtFree = parseFloat(document.getElementById('txtFreeBank').value);
var bankdetails = Parse.Object.extend("BankDetails");
var query = new Parse.Query(bankdetails);
query.equalTo("AccountNum", >>txtFree<<);
query.find({
success: function (results) {
alert("Successfully retrieved " + results.length + " scores.");
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('CustomerName'));
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
You will be able to access the data entered switching your >>txtFree<< for the following:
document.getElementById('txtFreeBank').value

Steam trade-offer-manager get items info shorten

I'm trying to build a new project.
It's going to be a tradebot for a website, now to store my received items into my database i whould like some info send with each item (being the name , asseid , tradeid,...).
The following code works.
offers.on('receivedOfferChanged', function (offer, oldState) {
logger.info(offer.partner.getSteam3RenderedID() + " Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
// Alert us when we accept an offer
if (offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function (err, items) {
if (err) {
logger.error("Couldn't get received items: " + err);
} else {
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
// Log a comma-separated list of items received
logger.info("Received: " + names + " " + assetids.join(', '));
}
});
}
});`
But the thing is, is there any way to shorten the following code :
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
So it gets the item name , assetid, ... out of the array and stores them in sperate variables ?
You can use push() method to add values into both arrays in a single loop. Try:
var names = [],
assetids = [];
items.forEach(function(item) {
assetids.push(item.assetid);
names.push(item.name);
});

Using objectid in JavaScript

I have a JavaScript table getting parse data need to use the objectid of each row for a later date need to store them in variable or something like that
Can any help me.
Cheers
UPDATE 1
Here is some code to help
var firstTeamResults = Parse.Object.extend(strUser);
var query = new Parse.Query(firstTeamResults);
query.startsWith("NameGame", ask4);
query.descending("updateAt");
query.find(
{
success: function(results)
{
for (var i = 0; i < results.length; i++)
{
var object = results[i];
(function($) {
$("#first-team-results-table").append("<tr><td>"
+ object.get("NameGame")
+ "</td><td>"
+ object.get("item")
+ "</td><td>"
+ "<input id='video' type='submit' value='Video'/>"
+ "</td><td>"
+ object.get("des")
+ "</td><td>"
+ object.get("group")
+ "</td><td>"
+ "<input id='more' type='submit' value='More'/>"
+ "</td></tr>");
})(jQuery);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
})
});
I think I understand what you're trying to ask. After you query the objects and get them, you can just call the .id method on each object to get the objectId.
See the example below.
var YourClass = Parse.Object.extend("YourClassName");
var query = new Parse.Query(YourClass);
//An unconstrained Query to get all objects in the table
query.find({
success: function(results) {
for(var i=0; i <results.length; i++){
var objectId = results[i].id //This returns you the objectId of each row
//You can do what you want with objectId now.
}
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
The Parse Docs show that you can retrieve the three special properties of every object by using the methods below.
var objectId = yourObject.id;
var updatedAt = yourObject.updatedAt;
var createdAt = yourObject.createdAt;

Why are the object values getting pushed into the array 3 times?

I have a simple object array into which I am pushing an object with 2 fields: bucketName and Date. The problem is that the values are getting pushed thrice into the array. Please help me.
JS:
sortBucket: function(bucketList) {
var counter, j = 0;
var str = "aws-billing-csv";
console.log("Bucket List :: ", bucketList);
bucketList.forEach(function(bucket, index) {
(function(bucketId) {
var bucketObj = {};
// console.log("Bucket Id :: ",bucketId);
s3Client.listObjects(params = {Bucket: bucketId }, function(err, data) {
var csvBucketArr = [];
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from ' + bucketID;
}
else{
//console.log("Bucket Data "+index+" :: ",data);
data.Contents.forEach(function(content,contentIndex){
var fileKey = content.Key;
if(fileKey.search(str) != -1) {
// console.log("fileKey["+bucketId+"] "+contentIndex+" :: ",fileKey + " Date :: " ,content.LastModified);
bucketObj[fileKey] = {
lastModified : content.LastModified,
bucketName : bucketId
}
if(!jQuery.isEmptyObject(bucketObj)){
csvBucketArr.push(bucketObj);
}
}
});
csv = csvBucketArr;
}
if(csvBucketArr.length!==0)
console.log("csvBucketArr :: ",csvBucketArr));
});
}(bucket.bucketName));
// console.log("Bucket " + index + " :: ", bucket);
});
},
You are pushing the same object into the array in each iteration of:
data.Contents.forEach(function(content,contentIndex){...});
So, as many times as that .forEach() loop iterates, you end up pushing the exact same bucketObj object into the csvBucketArr array.
If you want each iteration of that .forEach() to put a new and different bucketObj object into the array, then you need to create a new object each time inside that loop like this:
sortBucket: function(bucketList) {
var counter, j = 0;
var str = "aws-billing-csv";
console.log("Bucket List :: ", bucketList);
bucketList.forEach(function(bucket, index) {
(function(bucketId) {
// console.log("Bucket Id :: ",bucketId);
s3Client.listObjects(params = {Bucket: bucketId }, function(err, data) {
var csvBucketArr = [];
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from ' + bucketID;
}
else{
//console.log("Bucket Data "+index+" :: ",data);
data.Contents.forEach(function(content,contentIndex){
// ===> create new bucketObj object
var bucketObj = {};
var fileKey = content.Key;
if(fileKey.search(str) != -1) {
// console.log("fileKey["+bucketId+"] "+contentIndex+" :: ",fileKey + " Date :: " ,content.LastModified);
bucketObj[fileKey] = {
lastModified : content.LastModified,
bucketName : bucketId
}
if(!jQuery.isEmptyObject(bucketObj)){
csvBucketArr.push(bucketObj);
}
}
});
csv = csvBucketArr;
}
if(csvBucketArr.length!==0)
console.log("csvBucketArr :: ",csvBucketArr));
});
}(bucket.bucketName));
// console.log("Bucket " + index + " :: ", bucket);
});
},

Categories

Resources