sending a tricky array in a httpclient - javascript

I have to integrate data from an array into a webservice call which isn't the most efficient but it is what it is.
I have an array of ids (friend facebook ids).
I need to send these id's as parameters in a http client in titanium.
Due to Titanium having some trouble with passing arrays in webservices, I need to construct the send method of my http client as such:
non_xhr.send('user_id=100005941351187&friend_ids[0]=100000049956179&friend_ids[1]=100005272411678');
Obviousy depending on the user, they will have a different number of results to be stored in the array previously mentioned (of facebook friend ids).
I need help in how to integrate a loop based on the length of array mentioned above in order to construct the parameters needed, as described above.
All help appreciated.
I am using Titanium but for the purposes of this question, it is basically just javascript

How about creating your params like that:
function createParams(userId, friendIds) {
var output = "user_id=" + userId;
for(var i = 0, max = friendIds.length; i < max; i++) {
output += "&friend_ids[" + i + "]=" + friendIds[i];
}
return output;
}
You can find a working fiddle here.

Related

Understanding how to pull info from array

I have a previously created script that is doing API calls to get various info. Using json fetch. Its used to look up(GET) properties of users, groups, etc.
Here is how it prints. console.log(myArray):
[{user={conversion_id=smitht, ship_id=14.0, ship=Mountain , id=989, name=Smith, Todd, id=8745335.0, system_id=796663, login_id=todd.smith#domain.com,, created_at=3055-08-10, //keeps continuing for all users in this account
If I wanted to search the array and return only "name". Is there a better way to accomplish than this? This will print out just the names
for (let i = 0; i < myArray.length; i++){
console.log(myArray[i]['user']['name'])
I'm trying to learn what's possible and how to interact. Any other options to search through array? Most examples have sample arrays written out since mine comes from a response its been difficult to follow those examples.
use find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
function findByLoginId(loginId) {
const result = myArray.find(user => user.login_id === loginId);
return result?.name;
}
Check to make sure that the fetched data is valid JSON. You should be able to use JSON.parse on the returned data.

How can I return the step number [i] when a certain key-value pair is found in an array?

Super NOOB to javascript, so I need some help trying to parse this JSON object and return a specific value.
So I have a JSON payload from an API Call that I've turned into an object (sorry, I still don't know how to line break this so it shows easily here on Stack Overflow):
var myObj = JSON.parse("{'ClassID':'1ghjk2345','ProcessName':'Workflow','Steps':[{'Id':'1234ghjhg102','Name':'Start','ActivityInstanceID':'12435r3ffe2'},{'Id':'134gbvgg102','Name':'attendance','ActivityInstanceID':'7865fdghd'},{'Id':'1jhgy102','Name':'lesson','ActivityInstanceID':'12gs5ghdse2'},{'Id':'1ghkb102','Name':'quiz','ActivityInstanceID':'1sgdtgt'},{'Id':'12fkfh02','Name':'evaluation','ActivityInstanceID':'1243sdfgssdfg2'},{'Id':'1khfhf02','Name':'dismissal','ActivityInstanceID':'124sdfgdfgrrrfe2'}],'TimeTaken':54838,'_id':'PK21342ffh','status':'Complete'}");
I would like to return the Step number in the Array that contains this key-value pair:
'Name':'evaluation'
I need this because the order of the steps changes for each payload - sometimes it's step 4, sometimes 2 depending on when the teacher initiates that step in the application.
I would then like to retrieve the 'ActivityInstanceID' of that step.
You need to change your data do fit json requirements.
Use variables names in lower case.
var myData = JSON.parse('{"ClassID":"1ghjk2345","ProcessName":"Workflow","Steps":[{"Id":"1234ghjhg102","Name":"Start","ActivityInstanceID":"12435r3ffe2"},{"Id":"134gbvgg102","Name":"attendance","ActivityInstanceID":"7865fdghd"},{"Id":"1jhgy102","Name":"lesson","ActivityInstanceID":"12gs5ghdse2"},{"Id":"1ghkb102","Name":"quiz","ActivityInstanceID":"1sgdtgt"},{"Id":"12fkfh02","Name":"evaluation","ActivityInstanceID":"1243sdfgssdfg2"},{"Id":"1khfhf02","Name":"dismissal","ActivityInstanceID":"124sdfgdfgrrrfe2"}],"TimeTaken":54838,"_id":"PK21342ffh","status":"Complete"}');
for (let i = 0; i < myData.Steps.length; i++) {
if(myData.Steps[i].Name === "evaluation") console.log("the step is: ", i);
}

how to fetch all values in single variable using java script

i am retrieving the all values in a for loop but i want to insert those values in database using single variable.It possible to store all values to the single record.
var emailId;
//log.info("testing 1234 = "+tw.local.EntityProMasterList.listAllSelected);
for (var i = 0; i < tw.local.EntityProMasterList.listAllSelected.listLength; i++){
emailId = tw.local.EntityProMasterList.listAllSelected[i];
log.info("testing 1 = "+emailId.value);
}
log.info("testing 1 = "+emailId.value);
You can user JSON.stringify() and save it as string:
var holder = {};
holder.var1 = "var1";
holder.var2 = "var2";
log.info("holder:"+JSON.stringify(holder));
The output will be:
holder:{"var1":"var1","var2":"var2"}
I believe your question is - given a list of values, how can I insert those values into the database as separate entries. If this is correct there is a right way and a wrong way to do this.
The wrong way is to simply put all the SQL into a string and use one of the DB services in the system data toolkit to execute. Something like -
insert into table blah values(1, 2, 3, 4);
This would be wrong because you are open to SQL injection attacks. There is a different service for parameterized queries. This takes 1 or more SQL statements and a list of parameters to use in them. The details are documented in the service so I won't repeat them here. Basically you would modify your query to have the ? Character where you need the data from your array. You then create arrays of parameters that fill out the values on execution.

Create an array of JavaScript objects from an existing array of objects

my first time posting a question here, so please let me know if I'm missing any information that is needed. Updated to include desired output.
I'm working on a google app script (basically javascript) and am trying to pull objects from an array of objects and create a new array of objects. I'm using the google base functions for getRowData (these can be found at : https://developers.google.com/apps-script/guides/sheets) to create my initial array of objects. This gives me a row of data similar (A JIRA export if anyone is wondering, with information cut):
{summary=Internal - Fix PuppetFile Jenkins Jobs, progress=1.0, issueType=Story, resolution=Done, timeSpent=3600.0, key=XXXXX-646, watchers=0.0, remainingEstimate=0.0, numberOfComments=1.0, status=Resolved, assignee=XXXXXXXX}
When I run my function:
for (var i = 0; i < issueList.length; i++){
rankList[i] = [issueList[i].summary,issueList[i].storyPoints,issueList[i].epicLink,issueList[i].fixVersions];
}
I get:
[Internal - Fix PuppetFile Jenkins Jobs, 3.0, null, null]
But what I want is:
{summary=Internal - Fix PuppetFile Jenkins Jobs, storyPoints=1.0, epicLink=StoryName, fixVersions=Done}
I'm not getting the key for the value, and I don't understand how the objects are constructed quite well enough to get it to transfer over. I looked at some examples of manipulating the key/value pairs but when I tried it on my own I just got a bunch of undefined. Thank you for any help you can provide.
What you want is probably something like this:
rankList = [];
for (var i = 0; i < issueList.length; i++) {
issue = issueList[i];
rankList.push({
summary: issue.summary,
storyPoints: issue.progress,
epicLink: issue.IDONTKNOW,
fixVersions: issue.resolution
});
}
I don't know what field goes in epicLink, since it wasn't obvious from your example. And I was just guessing about the other fields. But this is the general structure, you just need to make all the correct correspondences.
Use jquery each instead it's much easier to get the keys and value at the same time:
var myarray = [];
$.each(issueList,function(key,value){
console.log(key);
console.log(value);
value.key = key;
myarray.push(value);
});
console.log(myarray);

javascript array.push inside for loop--result not array?

I'm trying to populate an array by using a for loop to access certain records in a database and then combine the contents of some DB fields with text to create each array element. Here's what I have:
var numbers = [7,8];
var phsw = [];
for (var i=0,len=numbers.length;i<len;i++) {
selectObj = cObj.select().from("wp_posts").where('ID=?', numbers[i]);
result1 = cObj.exec(selectObj);
var resource = result1[0].guid;
var title = result1[0].post_title;
var tnTxt = result1[0].post_title;
var tn = resource.replace(/\.jpg/,"-150x150.jpg");
phsw.push({mytitle:'" + title + "', mythumbnail:'" + tn + "', mytntxt:'" + tnTxt + "', myresource:'" + resource +"'});
}
This creates what I thought was an array, except it's apparently not really an array. When I use console.log(phsw) to see what's in it I get this:
[{mytitle:'title', mythumbnail:'imagefile1tnlink', mytntxt:'thumbtxt1', myresource:'imagefile1link'},{mytitle:'title2', mythumbnail:'imagefile2tnlink', mytntxt:'thumbtxt2', myresource:'imagefile2link'}]
where I should get this:
[object Object]
if it was really an array (right??).
I'm using this in Application Craft, and the phsw array is being created with server side javascript and then being passed to a callback on the application side, but when it gets back to the app side, I can't use it to populate a widget because it's not really an array. How can I make sure phsw is an array?
And yes, I'm sure this code isn't the most clean or efficient way to do this; my (rather rusty) experience is in PHP and MySQL as opposed to javascript, so I'm always open to suggestions of better ways to do things!
No everything is correct. It is in fact an array containing exactly 2 objects.
Your expectation that you should get [object Object] is wrong.

Categories

Resources