I have a MySQL database with two columns: Username and Password. I want to list usernames one by one.
The first function holds my database query:
msg.topic = "SELECT * FROM userlog";
return msg;
The second function loops until it displays all database usernames. maxarray is the maximum number of usernames in my database.
var maxarray = global.get("maxarray");
var i;
for (i = 0; i < maxarray; i++) {
msg.payload = msg.payload[i].Username;
node.send(msg);
}
return;
Whenever I run this, it gives me an error:
"TypeError: Cannot read property '2' of undefined"
Here's my flow if you would like to import.
[{"id":"213ba9d6.1ba576","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"820a48f5.ff49d8","type":"debug","z":"213ba9d6.1ba576","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":490,"y":100,"wires":[]},{"id":"673daf0e.c65b8","type":"inject","z":"213ba9d6.1ba576","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"\"SELECT * FROM userlog\"","payload":"","payloadType":"date","x":100,"y":100,"wires":[["3724e918.bf5b86"]]},{"id":"dbe2587d.cfb7a8","type":"mysql","z":"213ba9d6.1ba576","mydb":"f1e0508e.13503","name":"db","x":290,"y":100,"wires":[["fd991622.c20928"]]},{"id":"3724e918.bf5b86","type":"function","z":"213ba9d6.1ba576","name":"msg.topic","func":"msg.topic = \"SELECT * FROM userlog\";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":180,"y":140,"wires":[["dbe2587d.cfb7a8"]]},{"id":"fd991622.c20928","type":"function","z":"213ba9d6.1ba576","name":"for loop","func":"var i;\nvar array;\nfor (i = 0; i < msg.payload.length; i++) {\n msg.payload = array[i].Username;\n node.send(msg);\n}\nreturn;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":380,"y":140,"wires":[["820a48f5.ff49d8"]]},{"id":"f1e0508e.13503","type":"MySQLdatabase","name":"","host":"127.0.0.1","port":"3306","db":"test dump","tz":"","charset":"UTF8"}]
You need to take a copy of msg.payload before the loop as you've replaced it before sending the msg object.
You should probably also be using the array length rather than trying to keep track in a global variable
var i;
var array = msg.payload
for (i = 0; i < array.length; i++) {
msg.payload = array[i].Username;
node.send(msg);
}
return;
Related
Observe:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
The actual result in extendscript would be ... grouplinks ... empty.
If I would change this example to be:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
It would work perfectly. The only change is the missing "59" at the start of the string used for the array key.
Note that this works perfectly when I run it in console for chrome or firefox. It seems to be indesign and/or extendscript fooling around.
Anything have any ideas why ? I've meanwhile worked around the problem but I'm intrigued.
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
That's exactly what it does, but the way you're viewing the data is likely concealing it because you're not using the proper data structure. Also, property access won't work without using [] because identifiers may not start with a number, so you'd need:
groupedLinks["59notgonnawork0"]
What you're doing isn't meant for arrays, which are expecting sequential numeric indices (though they can technically be assigned other properties too). The type of structure you should be using is a plain object instead.
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
const linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array; // Array? plain Object? Depends on its use.
}
Why not trying to push the value in the array on each iteration.
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks.push(linkName);
}
ExtendScript Arrays are great for stocking data per indeces. If you need key/values objects, why not use… Objects ?
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = "Whatever…";
}
alert( groupedLinks["59notgonnawork0" ] ); //"Whatever…"
I am extremely new to programming and an assignment from class was to create a voting website. I was able to create variables and put them into local storage, as such:
var eventName = document.getElementById("eventName").value;
document.getElementById("p1").innerHTML = (eventName);
localStorage.setItem("eventName", eventName)
localStorage.getItem("eventName")
Now, we were supposed to include all of this into an array so that we can get multiple eventNames. My teacher is never really clear with his instructions, so this is what I got now:
var eventName = [];
var index ;
function submitNewEvent() {
eventName[index] = document.getElementById("eventName").value;
index = index + 1;
var eventNmString = JSON.stringify (eventName);
localStorage.setItem("eventName", JSON.stringify (eventName));
localStorage.getItem("eventName")
array = JSON.parse(localStorage.getItem("eventName"));
array = parse;
var output = "";
for (var i=0, array.length > i; i++){
output += "<p>"+array[i];
}
document.getElementById("p1").innerHTML = (output);
I would really appreciate any help if anyone can explain to me what I did wrong.
Here's the syntax error (the error message should point to that line as well):
for (var i=0, array.length > i; i++){
// ^
The array.length expression is not a valid identifier name, like i is (in a statement like var i=0, array=5; or so). You wanted to use a semicolon there:
for (var i=0; i < array.length; i++){
// ^
I've sent data from server side with socket.io :
for (i = 0; i<rows.length; i++) {
socket.emit('Switch', {eqid:rows[i].EquipmentID,eqroom:rows[i].Name});
}
and in the client side :
socket.on('Switch', function (data) {
console.log(data.eqid);
}
and what I get is :console log and when I do console.log(data.eqid[0] I get undefined
so I want to get an array [120336,120337..]
I've tried also to send an array from the beginning in the server side :
for (i = 0; i<rows.length; i++) {
var test=[];
test.push(rows[i].EquipmentID);
}
console.log(test);
console.log gives me the last equipmentID only [120339
console.log gives me the last equipmentID only [120339
Because you are redefining rows array in every iteration.
Try this:
var ids = [];
var names = [];
for (var i = 0; i < rows.length; i++) {
ids.push(rows[i].EquipmentID);
names.push(rows[i].Name);
}
socket.emit('Switch', {eqid: ids, eqroom: names});
(forgive me if I use slightly incorrect language - feel free to constructively correct as needed)
There are a couple posts about getting data from JSON data of siblings in the returned object, but I'm having trouble applying that information to my situation:
I have a bunch of objects that are getting returned as JSON from a REST call and for each object with a node of a certain key:value I need to extract the numeric value of a sibling node of a specific key. For example:
For the following list of objects, I need to add up the numbers in "file_size" for each object with matching "desc" and return that to matching input values on the page.
{"ResultSet":{
Result":[
{
"file_size":"722694",
"desc":"description1",
"format":"GIF"
},
{
"file_size":"19754932",
"desc":"description1",
"format":"JPEG"
},
{
"file_size":"778174",
"desc":"description2",
"format":"GIF"
},
{
"file_size":"244569996",
"desc":"description1",
"format":"PNG"
},
{
"file_size":"466918",
"desc":"description2",
"format":"TIFF"
}
]
}}
You can use the following function:
function findSum(description, array) {
var i = 0;
var sum = 0;
for(i = 0; i < array.length; i++) {
if(array[i]["desc"] == description && array[i].hasOwnProperty("file_size")) {
sum += parseInt(array[i]["file_size"], 10);
}
}
alert(sum);
}
And call it like this:
findSum("description1", ResultSet.Result);
To display an alert with the summation of all "description1" file sizes.
A working JSFiddle is here: http://jsfiddle.net/Q9n2U/.
In response to your updates and comments, here is some new code that creates some divs with the summations for all descriptions. I took out the hasOwnProperty code because you changed your data set, but note that if you have objects in the data array without the file_size property, you must use hasOwnProperty to check for it. You should be able to adjust this for your jQuery .each fairly easily.
var data = {};
var array = ResultSet.Result;
var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;
//Sum the sizes for each description
for(i = 0; i < array.length; i++) {
currentDesc = array[i]["desc"];
currentSize = parseInt(array[i]["file_size"], 10);
data[currentDesc] =
typeof data[currentDesc] === "undefined"
? currentSize
: data[currentDesc] + currentSize;
}
//Print the summations to divs on the page
for(sumItem in data) {
if(data.hasOwnProperty(sumItem)) {
sizeDiv = document.createElement("div");
sizeDiv.innerHTML = sumItem + ": " + data[sumItem].toString();
document.body.appendChild(sizeDiv);
}
}
A working JSFiddle is here: http://jsfiddle.net/DxCLu/.
That's an array embedded in an object, so
data.ResultSet.Result[2].file_size
would give you 778174
var sum = {}, result = ResultSet.Result
// Initialize Sum Storage
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] = 0;
}
// Sum the matching file size
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] += parseInt(result[i]["file_size"]
}
After executing above code, you will have a JSON named sum like this
sum = {
"description1": 20477629,
"description2": 1246092
};
An iterate like below should do the job,
var result = data.ResultSet.Result;
var stat = {};
for (var i = 0; i < result.length; i++) {
if (stat.hasOwnProperty(result[i].cat_desc)) {
if (result[i].hasOwnProperty('file_size')) {
stat[result[i].cat_desc] += parseInt(result[i].file_size, 10);
}
} else {
stat[result[i].cat_desc] = parseInt(result[i].file_size, 10);
}
}
DEMO: http://jsfiddle.net/HtrLu/1/
I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}