Node-Red String into payload name - javascript

My array payload is like: msg.payload[index].temp. I cut the array in single parts to publish the single parts of the array via MQTT.
So I got msg.payload.temp and msg.parts.index.
msg:{
payload:{
address: "e4:32:a3:3a:99:97";
temp: "32"
}
parts: {
type: "array";
index: "16";
count: "17";
}
}
Is it possible to put the number of the index into the name msg.payload.temp? So I got something like msg.payload.temp_6. I tried to combine strings together like:
var temp = "msg.payload.temp_" + msg.parts.index.toString();
temp = payload.temp;
return msg;
Do I need a conversation from string to json so Node-Red detect the property?

You can add a property to msg.payload.
let index = 6;
msg.payload["temp"+index] = 'Whatever';
This will be available as
console.log(msg.payload.temp6); // Whatever

Related

How to access object with a randomly chosen name stored in a variable?

I've got 16 objects with names like: aBoard, bBoard, cBoard and so on,
eg. let aBoard = { currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true };
I have an array of corresponding names, randomly chose one of them and change it so it matches the name of one of the objects.
const BOARDARRAY = ["unitA", "unitB", "unitC", "unitD", "unitE", "unitF", "unitG", "unitH", "unitI", "unitJ", "unitK", "unitL", "unitM", "unitN", "unitO", "unitP"];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
let temp = (currentBoardTile.charAt(currentBoardTile.length -1).toLowerCase());
JSObjectBoardUnit = (temp + "Board");
How to access the object using my JSObjectBoardUnit?
In other words, how to make JS "understand" that I want to treat JSObjectBoardUnit value (string) as a value of the object address?
Eg. Let's day JSObjectBoardUnit = aBoard;
Basically the outcome I want is: aBoard.key1 = JSObjectBoardUnit.key1.
I'd love to use the value stored in JSObjectBoardUnit to access the name of the predefined object aBoard.
I'm not sure to understand well your question but I think this 2 methode could maybe help you.
You can access attribute of a object with a string by using
const obj = {toto: 1};
const name = "toto";
console.log(obj["toto"]); // 1
console.log(obj[name]); // here we use variable and the result is 1
so you could store all yoyr object inside one and do this.
const allBoard = {
"aboard": null, // do not put null use your board
}
console.log(allBoard[(temp + "board")]); // display the temp + board attribute so if temps is equal to a then it will get the aboard
this is what you want, getting object from a string.
But I saw that the aboard also have an id attribute with "unitA"
Instead you could build an array of aboard, bboard ....
and use the Array.find() methode that will return the object that match the condition.
in your case
const myBoardArray = [{ currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true }, ....];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
myBoardArray.find((board) => board.ID === currentBoardTile);
2 options
Put the boards in a list, and iterate over them with a for loop. In the for loop, use an if statement to see which Id matches the board you want.
let boards = [aBoard , bBoard, cBoard];
boards.forEach(board=> {
if (board.ID == currentBoardTile) {
//do something
}
});
Create a dictionary where the key is the board id and the respective object is the value. Use the board id to get the respective value.
var boards = {
"unitA" : boardA,
"unitB" : boardB,
....
};
currentBoardTile = BOARDARRAY[randomizer];
console.log(currentBoardTile + " : " + boards[currentBoardTile]);

How to split string from number of / in node.js?

My sting is like this
console.log(fields.urlOfFolder); // console is [ '122/122/47/49/50' ]
and i want only first 122 how it is possible ?
i tried this code..
var customerid = fields.urlOfFolder.split('/')[0];
console.log(customerid);
but it gives error like this TypeError: fields.urlOfFolder.split is not a function
fields.urlOfFolder is an array. To access the first value from array, use fields.urlOfFolder[0]
var fields = {
urlOfFolder : [ '122/122/47/49/50' ]
};
var customerid = fields.urlOfFolder[0].split('/')[0];
console.log(customerid);
fields.urlOfFolder is an array with one entry, you need to pull the string out first:
var customerid = fields.urlOfFolder[0].split('/')[0];

Json key has '#' Special character

Currently I need the URL for an image and I am getting it through the JSON file. I am not sure to acquire the key that has the URL due to the key having a # at the start. Here is the JSON:
{
"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"small"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"medium"
}
Same as with every other time you encounter some JSON string!
The # is an invalid character in a property name, work around is the bracket notation: «object»[property] --> «array»[index]['#text'].
We can use forEach to extract the results.
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
var parsed = JSON.parse(string);
//parsed is an array, we can loop over it
parsed.forEach(function(obj) {
console.log(obj['#text']);
});
Even prettier would be if you can select from the array based on size:
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
function getImageUrlBySize(size, json) {
var parsed = JSON.parse(json);
return parsed.find(function(element) { //modern browsers only (no IE)
return element['size'] == size;
})['#text']; //add text here since find returns the full item
}
console.log(getImageUrlBySize('small', string));

How can I use underscore in name of dynamic object variable

Website that I'm making is in two different languages each data is saved in mongodb with prefix _nl or _en
With a url I need to be able to set up language like that:
http://localhost/en/This-Is-English-Head/This-Is-English-Sub
My code look like that:
var headPage = req.params.headPage;
var subPage = req.params.subPage;
var slug = 'name';
var slugSub = 'subPages.slug_en';
var myObject = {};
myObject[slugSub] = subPage;
myObject[slug] = headPage;
console.log(myObject);
Site.find(myObject,
function (err, pages) {
var Pages = {};
pages.forEach(function (page) {
Pages[page._id] = page;
});
console.log(Pages);
});
After console.log it I get following:
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Is you can see objectname subPages.slug_en is seen as a String insteed of object name..
I know that javascript does not support underscores(I guess?) but I'm still looking for a fix, otherwise i'll be forced to change all underscores in my db to different character...
Edit:
The final result of console.log need to be:
{ subPages.slug_en: 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Insteed of :
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Otherwise it does not work
The reason you are seeing 'subPages.slug_en' (with string quotes) is because of the . in the object key, not the underscore.
Underscores are definitely supported in object keys without quoting.
Using subPages.slug_en (without string quotes) would require you to have an object as follows:
{ subPages: {slug_en: 'This-Is-English-Sub'},
name: 'This-Is-English-Head' }
Which you could set with the following:
myObject['subPages']['slug_en'] = subPage;
Or simply:
myObject.subPages.slug_en = subPage;

In Firebase when using push() How do I pull the unique ID

I'm attempting to add/remove entries from a Firebase database. I want to list them in a table to be added/modified/removed (front end) but I need a way to uniquely identify each entry in order to modify/remove. Firebase adds a unique identifier by default when using push(), but I didn't see anything referencing how to select this unique identifier in the API documentation. Can this even be done? Should I be using set() instead so I'm creating the unique ID?
I've put this quick example together using their tutorial:
<div id='messagesDiv'></div>
<input type='text' class="td-field" id='nameInput' placeholder='Name'>
<input type='text' class="td-field" id='messageInput' placeholder='Message'>
<input type='text' class="td-field" id='categoryInput' placeholder='Category'>
<input type='text' class="td-field" id='enabledInput' placeholder='Enabled'>
<input type='text' class="td-field" id='approvedInput' placeholder='Approved'>
<input type='Button' class="td-field" id='Submit' Value="Revove" onclick="msgRef.remove()">
<script>
var myDataRef = new Firebase('https://unique.firebase.com/');
$('.td-field').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
var category = $('#categoryInput').val();
var enabled = $('#enabledInput').val();
var approved = $('#approvedInput').val();
myDataRef.push({name: name, text: text, category: category, enabled: enabled, approved: approved });
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
});
function displayChatMessage(name, text, category, enabled, approved, ) {
$('<div/>').text(text).prepend($('<em/>').text(name+' : '+category +' : '+enabled +' : '+approved+ ' : ' )).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
Now lets assume I have three rows of data:
fred : 1 : 1 : 1 : test message 1
fred : 1 : 1 : 1 : test message 2
fred : 1 : 1 : 1 : test message 3
How do I go about uniquely identifying row 2?
in the Firebase Database they look like this:
-DatabaseName
-IuxeSuSiNy6xiahCXa0
approved: "1"
category: "1"
enabled: "1"
name: "Fred"
text: "test message 1"
-IuxeTjwWOhV0lyEP5hf
approved: "1"
category: "1"
enabled: "1"
name: "Fred"
text: "test message 2"
-IuxeUWgBMTH4Xk9QADM
approved: "1"
category: "1"
enabled: "1"
name: "Fred"
text: "test message 3"
To anybody finding this question & using Firebase 3+, the way you get auto generated object unique ids after push is by using the key property (not method) on the promise snapshot:
firebase
.ref('item')
.push({...})
.then((snap) => {
const key = snap.key
})
Read more about it in the Firebase docs.
As a side note, those that consider generating their own unique ID should think twice about it. It may have security and performance implications. If you're not sure about it, use Firebase's ID. It contains a timestamp and has some neat security features out of the box.
More about it here:
The unique key generated by push() are ordered by the current time, so the resulting list of items will be chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).
To get the "name" of any snapshot (in this case, the ID created by push()) just call name() like this:
var name = snapshot.name();
If you want to get the name that has been auto-generated by push(), you can just call name() on the returned reference, like so:
var newRef = myDataRef.push(...);
var newID = newRef.name();
NOTE:
snapshot.name() has been deprecated. See other answers.
snapshot.name() has been deprecated. use key instead. The key property on any DataSnapshot (except for one which represents the root of a Firebase) will return the key name of the location that generated it. In your example:
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
var id = snapshot.key;
displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
});
To get uniqueID after push() you must use this variant:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique key generated by push()
var postId = newPostRef.key;
You generate a new Ref when you push() and using .key of this ref you can get uniqueID.
As #Rima pointed out, key() is the most straightforward way of getting the ID firebase assigned to your push().
If, however, you wish to cut-out the middle-man, Firebase released a gist with their ID generation code. It's simply a function of the current time, which is how they guarantee uniqueness, even w/o communicating w/ the server.
With that, you can use generateId(obj) and set(obj) to replicate the functionality of push()
Here's the ID function:
/**
* Fancy ID generator that creates 20-character string identifiers with the following properties:
*
* 1. They're based on timestamp so that they sort *after* any existing ids.
* 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs.
* 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly).
* 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, the
* latter ones will sort after the former ones. We do this by using the previous random bits
* but "incrementing" them by 1 (only in the case of a timestamp collision).
*/
generatePushID = (function() {
// Modeled after base64 web-safe chars, but ordered by ASCII.
var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
// Timestamp of last push, used to prevent local collisions if you push twice in one ms.
var lastPushTime = 0;
// We generate 72-bits of randomness which get turned into 12 characters and appended to the
// timestamp to prevent collisions with other clients. We store the last characters we
// generated because in the event of a collision, we'll use those same characters except
// "incremented" by one.
var lastRandChars = [];
return function() {
var now = new Date().getTime();
var duplicateTime = (now === lastPushTime);
lastPushTime = now;
var timeStampChars = new Array(8);
for (var i = 7; i >= 0; i--) {
timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
// NOTE: Can't use << here because javascript will convert to int and lose the upper bits.
now = Math.floor(now / 64);
}
if (now !== 0) throw new Error('We should have converted the entire timestamp.');
var id = timeStampChars.join('');
if (!duplicateTime) {
for (i = 0; i < 12; i++) {
lastRandChars[i] = Math.floor(Math.random() * 64);
}
} else {
// If the timestamp hasn't changed since last push, use the same random number, except incremented by 1.
for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
lastRandChars[i] = 0;
}
lastRandChars[i]++;
}
for (i = 0; i < 12; i++) {
id += PUSH_CHARS.charAt(lastRandChars[i]);
}
if(id.length != 20) throw new Error('Length should be 20.');
return id;
};
})();
You can update record adding the ObjectID using a promise returned by .then() after the .push() with snapshot.key:
const ref = Firebase.database().ref(`/posts`);
ref.push({ title, categories, content, timestamp})
.then((snapshot) => {
ref.child(snapshot.key).update({"id": snapshot.key})
});
If you want to get the unique key generated by the firebase push() method while or after writing to the database without the need to make another call, here's how you do it:
var reference = firebaseDatabase.ref('your/reference').push()
var uniqueKey = reference.key
reference.set("helllooooo")
.then(() => {
console.log(uniqueKey)
// this uniqueKey will be the same key that was just add/saved to your database
// can check your local console and your database, you will see the same key in both firebase and your local console
})
.catch(err =>
console.log(err)
});
The push() method has a key property which provides the key that was just generated which you can use before, after, or while you write to the database.
Use push() to get a new reference and key to get the the unique id of the it.
var ref = FirebaseDatabase.instance.ref();
var newRef = ref.push(); // Get new key
print(newRef.key); // This is the new key i.e IqpDfbI8f7EXABCma1t
newRef.set({"Demo": "Data"}) // Will be set under the above key
How i did it like:
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = mFirebaseDatabase.getReference().child("users").child(uid);
String key = ref.push().getKey(); // this will fetch unique key in advance
ref.child(key).setValue(classObject);
Now you can retain key for further use..

Categories

Resources