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

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.

Related

Adding an Individual JSON Object to an Array to Parse and Process

I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array
This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.

When to compare several Arrays in a 'for' loop

I'm still quite new to Javascript and Google Apps Script, and I'm attempting to create a script that takes your friends steam IDs, loops over their owned games, lists them to a spreadsheet, and displays if someone owns a game or not.
I've achieved the first part, looping over all of the owned games for each ID and adding them to an array if they don't already exist in the array works perfectly using:
var steamId = ['SomeSteamIDs'];
var gameIds = [];
var games = [];
function getGames(){
for (var i = 0; i < steamId.length; i++){
var response = UrlFetchApp.fetch("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=**YourSteamKey**&steamid=" + steamId[i] + "&format=json&include_appinfo=1");//Steam URL.
Logger.log('Response Code: ' + response.getResponseCode());//Checks the request actually connected.
var data = JSON.parse(response.getContentText());//Gets the plaintext JSON response and converts it to an object.
for (var n = 0; n < data.response.games.length; n++){//For the length of the games list
var code = data.response.games[n].appid;
var name = data.response.games[n].name;
if (gameIds.indexOf(code) === -1){//if the AppID doesn't appear in the 'appId' array and sub-arrays
gameIds[gameIds.length] = code;//then put it in the appId array for comparison
games[games.length] = [code,name];// and add the AppId and Game to the games array for writting.
};
};
}
var range = sheet.getRange("A2:B" + (gameIds.length + 1));//+1 here to compensate for starting on line 2, instead of 1.
range.setValues(games);//Perform one write action
}
This works perfectly in compiling a master list of games that are owned across all SteamIDs, but I'm having difficulty in finding a way of checking off what games are owned by each Individual ID, and what is not.
Initially I was experimenting with adding a 'Yes/No' string to the 'games' array when running the 'getGames' function, but any solution I come up with looses data. If I compare the values too early, the 'gameIds' array doesn't contain all of the data, so the first SteamID misses out on comparing against any games that the last SteamID owns.
If I do it too late, the 'data' variable only contains the response data from the last SteamID it checked, so I miss out on checking what games the first SteamID owns.
I've read the answer at How to compare arrays in JavaScript? several times now, but I'm still trying to figure out if I can use it to solve my issue.
Is there a way for me to achieve what I'm looking for, and what would be the most efficient way?
I would approach this a bit differently. I would keep an object of gameList with game object keys by id that have a name property and then userList property that is an array of users attached to each game. This will do a few things for you. One, you can lookup the game in constant time now instead of looping to find it in the array (which indexOf does). Two, you now have a unique list of games (all properties of a games object) with an array of user ids (who owns them) for easy lookup. here's the code of what I'm describing
var steamIds = [],
gameList = {};
function getGames(){
steamIds.forEach(function(steamId) {
var response = UrlFetchApp.fetch("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=**YourSteamKey**&steamid=" + steamId[i] + "&format=json&include_appinfo=1");//Steam URL.
Logger.log('Response Code: ' + response.getResponseCode());//Checks the request actually connected.
var data = JSON.parse(response.getContentText());//Gets the plaintext JSON response and converts it to an object.
data.response.games.forEach(function(game) {//For the length of the games list
var code = game.appid;
var name = game.name;
if (!gameList.hasOwnProperty(code)) {
gameList[code] = {name: name, userList: [steamId]};
} else {
gameList[code].userList.push(steamId);
}
});
});
}
Here's and example of the end result of what the gameList will look like when it's done
gameList : {
123: {
name: 'Some Game',
userList: [80, 90, 52]
},
567: {
name: 'Another Game',
userList: [68]
}
}
Writing to the cells will change a bit but your information is now associated in a way that makes it easy to get information about a particular game or users that own it.

Concatenate json arrays from localStorage and send to PHP

I am using localStorage to store some json arrays (no more than 25), and when the user logs out, I need to save the information stored in a MySQL database. Therefore, I am sending the data to a PHP script that is in charge of communicating and dealing with all the database stuff.
Anyway, I have been searching on the web, and I found here - Merge two json/javascript arrays in to one array - that I could just use concat.
I basically use this function:
function saveEverything() {
var localStorageData = "";
for (var i=0; i < localStorage.length; i++) {
localStorageData = localStorageData.concat(localStorage.getItem(localStorage.key(i)));
}
...
}
The ... represents the ajax bit that sends the localStorageData to a PHP script.
As you should know, localStorage doesn't store anything but strings, so I have to do JSON.stringify when I am setting the items. You might have noticed that I didn't do JSON.parse when concatenating the localStorage items into the localStorageData variable. I tried that before, and when I did alert(localStorageData) I only got [Object][object] ... (or something like that).
Anyway, with this kind of approach I am sending strings to php, and each json array is separated by line break. Is this the best/correct thing to do or should I have sticked to the JSON.parse way?
What does your JSON look like? concat is a method of Array instances, so you can only do this when you're working with an Array. Furthermore, JSON is a notation, to use it like this you would have to parse it back into JavaScript and then out again.
For example,
var json1 = '[{"foo":"bar"}]',
json2 = '[{"fizz":"buzz"}]';
var mergedJS = JSON.parse(json1).concat(JSON.parse(json2)),
mergedJSON = JSON.stringify(merged);
mergedJSON; // '[{"foo":"bar"},{"fizz":"buzz"}]'
If they're not Arrays, you might be able to get away with just wrapping them (depending on how you want the result), i.e.
var json1 = '{"foo":"bar"}',
json2 = '{"fizz":"buzz"}';
var mergedJSON = '[' + json1 + ',' + json2 + ']';
mergedJSON; // '[{"foo":"bar"},{"fizz":"buzz"}]'
Finally,
You might have noticed that I didn't do JSON.parse when concatenating the localStorage items into the localStorageData variable. I tried that before, and when I did alert(localStorageData) I only got [object Object]
[object Object] is the result of calling toString on almost any Object.
({}).toString(); // "[object Object]"
If you want to see something useful, use console.log and view the Console, or convert back to String with JSON.stringify.
alert(localStorageData) I only got [Object][object]
That's normal, you should stick with this previous version, build an object of objects and in the end use
JSON.stringify(localStorageData)
to send it as string.
function saveEverything(){
var localStorageData = {},
l = localStorage.length,
k;
for (var i=0; i < l; i++) {
k = localStorage.key(i);
localStorageData[k] = JSON.parse(localStorage.getItem(k));
}
return localStorageData;
}
Using object also makes it easier to distinguish these arrays, since you can also save keys under which they were saved.

sending a tricky array in a httpclient

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.

TaffyDB: Select problems

I'm new to TaffyDB and haven't done a lot of javascript programming so I'm hoping that the problem I'm having is something simple. I'm trying to update a listbox with the options stored in the TaffyDB according to the selected client. When I do my select however, it is returning all the rows.
Below is the code I am using to update the listbox, along with the selectString used to do the query, and what's in the TaffyDB.
Anyone have any ideas why I am getting back all rows when I specify clientID = 1788?
I tried the select string with and without quotes around the column identifier.
// load existing user client projects if we have any
var lbProjects = document.getElementById('lbProjects');
lbProjects.options.length = 0;
var selectString = '{clientID:"' + clientID + '"}';
alert(selectString);
userProjects(selectString).each(
function (r) {
var option = new Option();
option.value = r.projectID;
option.text = r.projectName;
lbProjects.add(option, null);
});
What's in selectString:
{clientID:"1788"}
What's in the DB:
[{"clientID":"1788","projectID":"19"},
{"clientID":"1789","projectID":"24"},
{"clientID":"1790","projectID":"23"}]
Thanks for any help.
Aaron L. Bratcher
The problem was trying to use the selectString variable.
The line
userProjects(selectString).each(
now reads
userProjects({clientID: clientIDValue}).each(
I was supposed to be passing in an object array, not a string. {} in javascript creates an array of objects.

Categories

Resources