How to add to an array in Cloud Code?
-
I'm 100% not sure how to add a string to an array of strings. Nothing is hard coded so I can't just write a raw array, I need to reference two different variables and add them together and I can't seem to figure it out.
In GameSparks it was as easy as just calling push, but either I get an error or I end up with a number as a result.
For example if I was to try and just push the string "purchaseToAdd" the result is an integer which is the length of the array and not the actual array itself. There's nothing in the API for this relatively simple function.function GetPurchases(purchaseToAdd) { var entityType = "Purchases"; var entityProxy = bridge.getEntityServiceProxy(); var newPurch = []; newPurch = newPurch.push(purchaseToAdd); var postResult = entityProxy.getSingleton(entityType); if (postResult.status == 200) { var entId = postResult.data.entityId; var jsonData = []; for (var i = 0; i < postResult.data.data.purchases.length; i++) { jsonData = jsonData.push(postResult.data.data.purchases[i]); } //jsonData = Array.prototype.slice.call(postResult.data.data.purchases); jsonData = jsonData.push(newPurch); var jsonEntityData = { "purchases": Array.prototype.slice.call(jsonData) };
-
I posted this almost 13 days ago with zero answers, so I took some time to look through a bunch of documentation and did a ton of trial and error. Please Braincloud for the love of god add this to your API.
Rhino does not handle Arrays the way that other coding languages do.
I figured it out, unlike most arrays that return an array after you call push- Rhino returns the new length. So if you call push, don't set it's value.
var copyArray = []; //I assume this line tells it to be an array for (var i = 0; i < postResult.data..length; i++) { copyArray[i] = postResult.data[i]; //arrays do not behave like .Net arrays, you can change length without initializing, so you just set each index to the index of the array you're copying } copyArray.push(variableToAdd); //Do NOT set this as the value of your array, the push method returns an int (length of array) NOT an array! //you probably dont need to call push at all to add to the array as shown in the for loop above if you already know your length or want a specific length
Then just set your value to the variable, like this
var entityData = { "variableName": copyArray }; //No need to call Array(copyArray) or any of the prototype. slice stuff. If you call Array() you'll just nest the array a second time.
Use this page for further info on functions you can do with arrays.