create an array from different objects - javascript

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

Related

Increasing the msg.payload[i] variable

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;

Unable to access json values

I have a JSON array from ajax response but when I tried to access it field then it says undefined.
here is my JSON
[{"material_name":1042,"qty_per_piece":"30","material_qty_req":150},{"material_name":1043,"qty_per_piece":"20","material_qty_req":100},{"material_name":1041,"qty_per_piece":"10","material_qty_req":50}]
what i am trying its following
for(var j = 0; j<material.length; j++){
var matName = material.material_name[j];
alert(matName);
when i tried through following it shows undefined
for(var j = 0; j<material.length; j++){
var material_names = material[j].material_name;
alert(material_names);
var material = [{"material_name":1042,"qty_per_piece":"30","material_qty_req":150},{"material_name":1043,"qty_per_piece":"20","material_qty_req":100},{"material_name":1041,"qty_per_piece":"10","material_qty_req":50}];
material.forEach(function(v,k){
console.log(v.material_name);
});

JS check if the value of object exists

So, I have following js setup:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
Then,
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (NAMES[my_name] !== 185){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}
alert(JSON.stringify(NAMES , null, 4));
Here is a screenshot of the alert:
I hardcoded the number "185" for this example. I need to check if the id of 185 exists, then skip to else. I am not sure how to check it. I tried typeof, undefinedetc. but no luck.
(In other words, I should only have one "185").
Any help? Thanks!
If I understood correctly what you are trying to achieve, you have to iterate over NAMES and check every element. For example, you could do it using [].some javascript function:
if (!NAMES.some(function(v){return v[my_name]})) {
...
} else {
}
If you want to remove duplication you can just use NAMES as an object instead of array like this
var all_names = [185, 185, 181],
NAMES = {};
for (var j = 0; j < all_names.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
NAMES[my_name] = ["sean","sdfsd","sdfsfd"];
}
alert(JSON.stringify(NAMES, null, 4));
First of all I would recommend making a JS Fiddle or CodePen out of this so people can see the code running.
I believe that the issue is that NAMES[my_name] is not doing what you think it is. NAMES is an Array so when you say NAMES[my_name] you are really asking for the ITEM in the array so you are getting the entire object that you create in the INFO function. What you really want is to see if the object has an attribute that matches the value (e.g. "185" from the my_names array).
This is not the prettiest code but it will show you how to do what you really want to do:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
all_names = ["185", "186", "185"]
for (var j = 0; j < all_names.length; j++) {
var my_name = all_names[j];
if (NAMES.length == 0) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
} else {
var match = false;
for (var x = 0; x < NAMES.length; x++) {
console.log(NAMES[x][my_name] + ' : ' + my_name);
if(NAMES[x][my_name]) {
match = true;
}
}
if (!match) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}
}
}
alert(JSON.stringify(NAMES , null, 4));
Note the if that looks at NAMES[x][my_name] - this is asking if the item at array index 'x' has an attribute of 'my_name' (e.g. "185"). I believe this is really what you are trying to do. As its after midnight I assure you that there is more concise and pretty JS to do this but this should show you the basic issue you have to address.
Try this code using hasOwnProperty method :
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (!NAMES[my_name].hasOwnProperty("185")){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}

json sibling data

(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/

Finding an object and returning it based on search criteria

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

Categories