Steam trade-offer-manager get items info shorten - javascript

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

Related

Loop inside loop producing wrong result

I'm having trouble producing a script to match an object's value in object array based on an object's value in a separate array, and retrieve a separate value from that object.
I have used standard for-loops and the current iteration in jQuery each.
I have also tried setting the if statement to look for the two values as ==, but it always produces non matches (or -1).
Can anyone steer me in the right direction here?
transfers = [
{Package: "1", Origin_Facility = "a"},
{Package: "2", Origin_Facility = "b"}
];
storeData = [
{fromPackage: "1,6,26"}
]
var storeDataEach = function( sx, sxv ) {
var transfersEach = function( sy, syv ) {
if(storeData[sx].fromPackage.indexOf(transfers[sy].Package) > -1){
var facilityStore = transfers[sx].Origin_Facility;
storeData[sx].origin = facilityStore + " + " + transfers[sy].Package + ' + ' + storeData[sx].fromPackage;
return false;
} else {storeData[sx].origin = 'error' + transfers[sy].Package + " + " + storeData[sx].fromPackage;return false;}
};
jQuery.each(transfers, transfersEach);
}
jQuery.each(storeData, storeDataEach);
The main problem is you are returning false from the $.each loop which will stop the iteration
A crude fix is to remove the return from else block
var storeDataEach = function(sx, sxv) {
var transfersEach = function(sy, syv) {
if (storeData[sx].fromPackage.indexOf(transfers[sy].Package) > -1) {
var facilityStore = transfers[sx].Origin_Facility;
storeData[sx].origin = facilityStore + " + " + transfers[sy].Package + ' + ' + storeData[sx].fromPackage;
return false;
} else {
storeData[sx].origin = 'error' + transfers[sy].Package + " + " + storeData[sx].fromPackage;
}
};
jQuery.each(transfers, transfersEach);
}
But this still have problems with the data structure, in your example you have 26 in the fromPackage, now if you have a package value of 2 that also will return a positive result

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

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

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

how to run javascript object from string without using eval()

i have a json object that has item type and id, i need to create new object
var data = {
"items":[
{"type":"generator","id":"item_1","x":200,"y":200},
{"type":"battery","id":"item_2","x":50,"y":300},
{"type":"generator","id":"item_3","x":200,"y":280},
{"type":"battery","id":"item_4","x":100,"y":400}
]
};
and i need to run for each item in items
jQuery.each(data.items, function(index,value) {
eval("var " + value.id + " = new " + value.type + "(" + (index + 1) + ");");
eval(value.id + ".id = '" + value.id + "';");
eval(value.id + ".draw(" + value.x + "," + value.y + ");")
});
this is not a good practice, but what else can i do?
i need then to have the control on the items
something like
item_1.moveto(300,700);
but i always get item_1 is undefind
You can create a factory method which allows to generate concrete types out of an abstract data structure:
var createItem = (function () {
var types = {};
function createItem(index, data) {
data = data || {};
var ctor = types[data.type], item;
if (!ctor) throw new Error("'" + data.type + "' is not a registered item type.");
item = new ctor(index);
item.id = data.id;
return item;
}
createItem.registerType = function (type, ctor) {
types[type] = ctor;
};
return createItem;
})();
Then register item types to the factory:
function Generator(index) {/*...*/}
createItem.registerType('generator', Generator);
And finally create an object map to lookup your items by id (you could use a specialized object like ItemsMap instead of a plain object), loop through your items and add them to the map.
var itemsMap = {};
data.items.forEach(function (itemData, i) {
var item = itemsMap[itemData.id] = createItem(i + 1, itemData);
//you can also draw them at this point
item.draw(itemData.x, itemData.y);
});
You can now lookup objects by id like:
var item1 = itemsMap['item_1'];
var objects = {};
objects[value.id] = new window[value.type](index + 1);

Iterating a JSON return properly

I have a strange problem with my script. I am getting a JSON result set and want to iterate it and then display in a div. I checked fiddler and I can see the entire set being returned like the set below
[{"EPubID":71,"SerialID":1,"PartnerID":343,"Partner":"Aberdeen, City of ","PublicationTitle":"Uploading multiple files test","AuthFirstName":null,"AuthMiddleName":null,"AuthLastName":null,"AuthFullName":null,"PublicationYear":2011,"SubmitterEmail":null,"VolumeNumber":null,"Issue":null,"AlreadyInCatalog":false,"InCatalog":"No","Status":"D","Notes":"testing multiple file uploads","IsMonograph":false,"Monographed":"No","SubmittedDate":"\/Date(1317913458810)\/","SubmittedBy":"admin","ApprovedDate":"\/Date(1317914842263)\/","ApprovedBy":"admin","SubmittingPartnerID":0,"OriginalRefId":"343-71","SerialName":"None","URL":null,"InfoRecordID":0,"LastModified":"\/Date(-62135568000000)\/","IsSerial":false,"Approved":false,"Delete":false,"Pending":false,"files":null},{"EPubID":72,"SerialID":19,"PartnerID":26,"Partner":"Digital Archives","PublicationTitle":"testing multiple file uploads ","AuthFirstName":null,"AuthMiddleName":null,"AuthLastName":null,"AuthFullName":null,"PublicationYear":2001,"SubmitterEmail":null,"VolumeNumber":"1","Issue":"1","AlreadyInCatalog":false,"InCatalog":"No","Status":"A","Notes":"this should work","IsMonograph":false,"Monographed":"No","SubmittedDate":"\/Date(1317915134767)\/","SubmittedBy":"admin","ApprovedDate":"\/Date(1317915430627)\/","ApprovedBy":"admin","SubmittingPartnerID":0,"OriginalRefId":"26-72","SerialName":"Fake Test Serial","URL":null,"InfoRecordID":0,"LastModified":"\/Date(-62135568000000)\/","IsSerial":false,"Approved":false,"Delete":false,"Pending":false,"files":null}]
The problem is my script is only displaying the first item returned and nothing else. Here is my script.
function SearchExistingEpubs() {
var title = $("input#PublicationTitle").val();
$('#Results').hide();
$("div#SearchResults").innerHTML = '';
$.getJSON('/EPub/SearchExistingEpubs/' + title, null, function (data) {
var items = [];
var found = false;
$.each(data, function (key, val) {
found = true;
$("div#SearchResults").empty();
$("div#SearchResults").append("Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear) ;
$('#Results').show();
});
if (!found) {
$("div#SearchResults").empty();
//$("div#SearchResults").html('');
$("div#SearchResults").append("No documents found");
$('#Results').show();
//$('#Results').slideUp(10000);
$('#Results').animate({height:'toggle'},10000);
//$('#Results').fadeOut(10000);
}
//$('#Results').show();
});
};
You're wiping out the contents of the div in each iteration of the loop with your call to empty():
$.each(data, function (key, val) {
found = true;
$("div#SearchResults").empty(); // <------ REMOVE this line
$("div#SearchResults").append("Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear) ;
$('#Results').show();
});
But doing dom updates in a loop is not usually a good idea. Why not build up your string and do one dom update:
var content = '';
$.each(data, function (key, val) {
found = true;
content += "Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear;
});
$("div#SearchResults").append(content);
$('#Results').show();
In your .each loop you're calling $("div#SearchResults").empty(); this will clear any content you've previously appended to this div.
Try the following:
function SearchExistingEpubs() {
var title = $("input#PublicationTitle").val();
$('#Results').hide();
$("div#SearchResults").empty();
$.getJSON('/EPub/SearchExistingEpubs/' + title, null, function (data) {
$("div#SearchResults").empty();
var items = [];
if (data.length) {
$.each(data, function (key, val) {
$("div#SearchResults").append("Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear);
});
$('#Results').show();
} else {
$("div#SearchResults").append("No documents found");
$('#Results').show();
$('#Results').animate({height:'toggle'},10000);
}
});
};

Categories

Resources