node red array / how to "use" specific place - javascript

in node red i collect values with "Collector" the collector sends me an "Object" with all pairs of values when one of them is updated:
{ "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
with "json" and after with "stringsplit" i got an array of f.e. 9 values:
array [9] (can be up to 80 pairs of values)!
[ "{", "mqtt/1/", ":", "-127.00", ",", "mqtt/0/", ":", "41.61", "}" ]
now i want to have a function node which compares the Value (-127.00) from the Topic (mqtt/1/) with the Value (41.61) from the Topic (mqtt/0/).
this i working ...BUT only if i know which is the first topic/value and which is the second...
var outputMsgs = msg.payload;
var top1=outputMsgs[1];
var val1=outputMsgs[3];
var top2=outputMsgs[5];
var val2=outputMsgs[7];
msg = {payload: val1}
var msg2 = {payload: val2}
if (val1>val2)
{var msgOUT={payload: "BIGGER"};}
return [msg, msg2, msgOUT];
But the Problem is, that sometimes "mqtt/1/" comes first, sometimes "mqtt/0/" and values will be switched. So now, maybe somebody can help to write a function to pick the right value with the right topic to compare them in the next step.
Maybe is there a Way to look if the topic contains 0, 1 ...80, and then save it in this order in a array???
Thank you in advance!

If the initial msg.payload is truly a javascript object as you describe, ie:
msg.payload = { "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
then you can reference the two values as:
var value1 = msg.payload["mqtt/1/"];
var value1 = msg.payload["mqtt/2/"];
If msg.payload is actual a JSON string, then pass the message through a JSON node first to convert it to the object.
There is no need to try splitting the string yourself and parsing the content.

Related

Javascript/Google Apps Script IndexOf issues [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
There are a couple of similar queries here about the IndexOf function, but I'm reaching out because although the answers provided have been helpful, none of them have solved the issue.
I have a (very) large 2d array from a spreadsheet of names vs id codes. I read these values in apps script into an array (rIdr in the snippet below).
I then build 2x one-dimensional arrays so that I can use IndexOf to search for a name in the first array then use the returned index it to pull out the value from the second array.
var keys=[]; var vals=[];
//build key-val lookup arrays
for (var i = 0; i < rIdr.values.length; i++){
var k = rIdr.values[i][0].toString()
keys[i]=k
var v = rIdr.values[i][1].toString()
vals[i]=k
}
The name I'm looking for is obtained from a JSON which is populated elsewhere. I iterate over the names in this object, looking for them in my key and val arrays:
jsonobj.data.forEach(function(value) {
var idx = keys.indexOf(value.first_names_txt + " " + value.last_name_txt)
var id = -1;
if (idx > -1){id = vals[idx]}
Logger.log(value.first_names_txt + " " + value.last_name_txt + " " + id)
});
I've verified that both the name i'm pulling out of the JSON object as well as the elements of the keys array are String types. I've seen in the object inspector that the keys array is an array of strings (not, for example, an array of array objects).
Try as I might, i can't get IndexOf to return anything other than -1.
Even if I explicitly look for a name which I know is in there (and actually is a copy paste of the name as it's written on the sheet that I'm pulling values from), I still get -1 returned
var test
test = keys.indexOf("Joe Bloggs")
I'm tearing my hair out here. I don't want to write a separate function to match a name in the keys array, because I'll either need to pass in the full keys array as an argument, or make it a global variable - neither of which i want to do for various reasons.
Can anyone help with why IndexOf doesn't work here?
And if this is an issue that won't go away, is there a way to write my own search function which avoids passing large arrays around or declaring them as global variables?
Thanks all in advance
Description
I've constructed a spreadsheet sheet using the names from the json data file, randomized the names so they are no longer in alphabetical order and then assigned an id number to each.
The sample script I've provided lists the id number for the names in the json data file. Notice I'm working with the original data array. I don't need to create key value arrays to get the result I want. And I'm not checking if a name doesn't exist in the data array.
I've truncatd the json data for brevity
Code.gs
function test_json() {
try {
let jdata = {
"type" : "entrants",
"data" : [ {
"type" : "entrant",
"id" : "en_tdgwjajthr",
"first_names_txt" : "Archie",
"last_name_txt" : "White",
"entrytype" : "et_dv8u152j",
"answers" : {
"q_wg5qq6bgvsy90rh" : "Partenza Nude-Espresso RT"
}
}, {
.
.
.
.
}, {
"type" : "entrant",
"id" : "en_8uhauoe3jo",
"first_names_txt" : "Valentijn",
"last_name_txt" : "Brax",
"entrytype" : "et_dv8u152j",
"answers" : {
"q_wg5qq6bgvsy90rh" : "Dulwich Paragon CC"
}
} ],
"has_more_bool" : false
};
let values = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test").getDataRange().getValues();
jdata.data.forEach(function(value){
let key = value.first_names_txt+" "+value.last_name_txt;
let found = values.find( row => row[0] === key );
console.log("key = "+key+" id = "+found[1]);
});
}
catch(err) {
console.log(err)
}
}
Execution log (abbreviated)
10:29:05 AM Notice Execution started
10:29:06 AM Info key = Archie White id = 21
10:29:06 AM Info key = ari panzer id = 15
10:29:06 AM Info key = Daniel Mulcahy id = 5
10:29:06 AM Info key = David Streule id = 12
10:29:06 AM Info key = Dominic Bell id = 10
10:29:06 AM Info key = Euan Davies id = 14

Printing JSON Data into innerHTML getting undefined - [object]

Hi guys Im trying to print a list of scores saved within a database, ive got the data as JSON data (see below)
I am trying to print all each object within the "Scores" array using the following code
function showScores() {
var ourRequest = new XMLHttpRequest();
var x, i = "";
ourRequest.open('GET', '/allScores');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
for (i in ourData.scores) {
x += ourData.scores[i] + "<br>";
}
document.getElementById("scoresList").innerHTML = x;
};
ourRequest.send();
}
However it is printing out the following
Any help with this is greatly appreciated, thanks guys
This line tries to append a raw object to your HTML string:
x += ourData.scores[i]
Javascript can’t magically parse this into HTML for you, so it just outputs [object Object].
You need to build a string from the individual parts of this object and print that instead. For example:
Note that you should not use for ... in with an array
ourData.scores.forEach(function (score) {
x += `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
});
Which would output something like this for each score:
[H] Arsenal 2 - 2 Newcastle [A]
Be sure to set x = "" before the loop otherwise the string will still start with undefined.
In case you’re interested: there are more succinct ways of writing this loop. Using Array.map() for instance:
let x = ourData.scores.map(score => {
return `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
}).join();
This expression does not require initialization of x beforehand.
you can create the elements as string and you can join the entire array and assign it to the innerHTML, as shown below.
You can change the structure, here for example i had made to ul , li you can create table or whatever format.
Note if you want to just append it, since the object you can't directly append it using JSON.stringify which will convert your object into string.
I hope this will solve your issue. Please let me know if any other issue you are facing.
var jsonObj = {scores: [{"Away_Score": 2, "Away_Team": "Newcastle", "Home_Score": 2, "Home_Team": "Arsenal"}, {"Away_Score": 2, "Away_Team": "Napoli", "Home_Score": 4, "Home_Team": "Liverpool"}]}
var html = jsonObj.scores.map(o => {
return `<ul><li>${o.Away_Team}</li><li>${o.Away_Score}</li><li>${o.Home_Team}</li><li>${o.Home_Score}</li></ul>`
})
document.getElementById("todaysData").innerHTML = html.join("")
<div id="todaysData">
</div>

Javascript map CSV string to JSON array

this one baffles me and I'm not even sure I'm searching the correct keywords for possible explanations.
I am sending an RPC to a remote server. The response I get is just a comma-delimited string with values (no keys) like so:
val1,val2,val3,val4,val5,val6,val7,val8,val9
When I receive this response I need to map these values through JS to keys (hard-coded, I designate) and generate a JSON array like this:
{
"response": {
"mykey1" : "val1",
"mykey2" : "val2",
"mykey3" : "val3",
"mykey4" : "val4",
"mykey5" : "val5",
"mykey6" : "val6",
"mykey7" : "val7",
"mykey8" : "val8",
"mykey9" : "val9"
}
}
Can anybody nudge me in the right direction...sample code or tutorials that are close to what I am looking for? This is a for middleware script that gets called when server receives the response.
This is my first post here, been looking a long time learning and applying in Obj-C and as I am learning Swift, but JS is new to me. I apologize in advance if I am breaking any protocols by asking for help without posting my feeble attempts at figuring this out...
You can split the response on comma, which will give you an array.
Since both arrays (keys and vals) are the same length, you can loop over either and create your array of objects that way. See below
var response = 'val1,val2,val3,val4,val5';
var keys = [
'key1', 'key2', 'key3', 'key4', 'key5'
];
var dict = [];
var vals = response.split(',');
vals.forEach(function(val, i) {
dict[keys[i]] = val;
});
console.log(dict);
Read my comment, then check this out:
var result = 'val1,val2,val3,val4,val5,val6,val7,val8,val9';
// real question should be why result is not JSON already
var resArray = result.split(',');
console.log(resArray[0]); // first result
console.log(resArray[1]); // second result

Split an object into array of objects based on a condition in JavaScript

How to split an object into array of objects based on a condition.
oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225}
Above is the given sample object. I want to make an array of objects like this,
newArray = [{"city":"Chicago", "similarTo":"Myrtle"},
{"city":"Portsmouth", "similarTo":"Rock Hill"},
{"city":"Columbia", "similarTo":"Laconia"},
{"city":"Council Bluffs", "similarTo":"Derry"}]
I have been scratching my head with this for a while now. How can I get the above array(newArray)?
Here is a bunch of code you can try.
1) Iterate over oldObject and get the name of the property.
2) Split that name into an array based on the ":" character, since it separates the cities
3) Go over that new array, splitting it on the "," character (so as not to get the states).
4) Put the values into the newObject, based on whether it's the first or second part of the original property name.
5) Push that newObject, now with items, into a newArray.
Basically, this parses apart the name and does some array splitting to get at the right values. Hope it helps and helps you understand too.
var oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225};
var newArray = [];
for (object in oldObject) {
var thisObjectName = object;
var thisObjectAsArray = thisObjectName.split(':');
var newObject = {
'city': '',
'similar_to': ''
};
thisObjectAsArray.forEach(function(element,index,array) {
var thisObjectNameAsArray = element.split(',');
var thisObjectNameCity = thisObjectNameAsArray[0];
if(index===0) {
newObject.city = thisObjectNameCity;
} else if(index===1) {
newObject.similar_to = thisObjectNameCity;
}
});
newArray.push(newObject);
}
console.log(newArray);
PS: to test, run the above code and check your Developer Tools console to see the new array output.

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...

Categories