In nodeja/nodered, how do i address this property? - javascript

I want to use this property in my function node. How do i address this property? msg.payload.tagData.???

You will need to use the square bracket notation:
msg.payload.tagData['0828CA741AEEB01700172093000004E3'].inIntensity

msg.payload.tagdata['0828CA741AEEB01700172093000004E3']
if its dyanmic and you only need to access the first property, you can do
msg.payload.tagData[0]
if you want to dynamically get all of the data of those properties, you can loop through them

I was looking for the keys operator. This worked for me:
payload=msg.payload;
for(let key in payload.tagData) {
payload.tagData[key].epc = key;
}
return msg;

Those are hexadecimal attributes, you might need to convert them to decimal before you can access them
const hexes = [
'44c7b3b30db9c13b5',
'68b739c1c6ca2bf7a',
'f8fde53b68ee6b9eb',
'7f61b32d42b4bed47',
'f463cb64441e85a81',
]
let obj = {}
hexes.map((hex, i) => obj[`0x${hex.toUpperCase()}`] = i)
console.log(obj)

Related

How to get the name from the array in javascript?

I am fairly new to JavaScript and I am trying to extract the name Sam from the array. The output that I'm getting is name. How do I get Sam? Thank you in advance. I apologize but I know this is a fairly novice question.
I am trying to loop by using forEach.
let Person = {
name: ['Sam']
}
let handler = Object.keys(Person)
handler.forEach(function(element){
console.log(element)
})
Object.keys() only gives you keys
Use Object.entries() if you want key and value
Use Object.values() if you only want values
let Person = {
name: ['Sam']
}
for (const fn of ["values", "keys", "entries"]) {
console.log(`Using: Object.${fn}()`);
for (const v of Object[fn](Person)) {
console.log(v);
}
}
Instead of Object.keys use Object.values
If you know in advance that your name array is located under the key name, then access it directly
const person = { name: ['Sam'] };
console.log(person.name);
console.log(person.name[0]);
Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for:
const person = { name: ['Sam'], anotherProp: 'hello' };
console.log(Object.values(person));
Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly.
let Person = {
name: ['Sam',"Bob","Alice"]
}
let count = Person.name.length;
for(let i = 0; i<count; i++){
console.log( Person.name[i])
}
If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation.
Object.keys(obj).forEach(key => obj[key]);
let Person = {
name: ['Sam']
}
Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`));

Object map Javascript

I have a object map in JavaScript and I have to read it.
The object map is:
network[0]
Object {dpi: "user2"}
I have used this to read the key:
demp=Object.keys(network[0]);
sourceNodeFirewall = demp[0];
But I'm not able to read the value ("user2").
I know that I can do this:
network[0].dpi
in order to have user2, but during a for cycle I have no idea to do it, in addition that the key can change in any value.
I cannot put the real code because it is very complicate but an simple example is:
The object is set in this way:
var network = {};
network[$("#0B").val()] = $("#0BB").val();
Where I have a key and I value.
After that I wish to get the value and the key.
demp stores all key of the object, You need to access the property from the network[0] object.
var network = [{dpi: "user2"}];
demp = Object.keys(network[0]);
console.log(network[0][demp[0]]);
You can access an object's properties by indexing into it with square brackets:
var network = [{dpi: "user2"}];
console.log(network[0]);
var demp = Object.keys(network[0]);
var sourceNodeFirewall = demp[0];
var propValue = network[0][demp[0]];
console.log(propValue);
In a for loop you need to iterate over each key in the map, and to access the value just lookup the map with that key as the index.
var network = {
dpi: "user2"
}
for (var key in network) {
console.log(network[key]);
}
As you referred to a for loop, here what I think you are looking for:
const obj = {
dpi: "user2"
};
for(key in obj){
console.log(obj[key]);
}
Or maybe using a forEach:
const obj = {
dpi: "user2"
};
Object.keys(obj).forEach(
key => console.log(obj[key])
)

Add dynamic key, value pairs to JavaScript array or hash table

I'm trying to add a key value pair to an existing javascript associative array. The key needs to be a variable. This is for JSON encoding. I realize there are many plugins and frameworks for this, but I want a simple answer.
ary.push({name: val});
where ary is a new array, name is a variable containing the key, val is the value of this entry.
I'm doing this in a jQuery loop that iterates through form fields.
In ES6...
In ES6, you can use a destructuring assignment;
ary.push({[name]: val});
However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.
Without ES6 (legacy browser support)...
You need to define an object and use square bracket notation to set the property;
var obj = {};
obj[name] = val;
ary.push(obj);
If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.
var ary = [];
function pushToAry(name, val) {
var obj = {};
obj[name] = val;
ary.push(obj);
}
pushToAry("myName", "myVal");
Having just fully read your question though, all you need is the following
$(your collection of form els).serializeArray();
Good old jQuery
An "associative array" is really just an object. You don't use push, you just assign properties to the object:
ary[name] = val;
The following code will help you
ary.push( {[name]: val} );
See below example
let allData = [{name: "Cat", type: "Animal"}]
let finalData: any = [];
for (let i = 0; i < allData.length; i++)
{
let obj = allData[i];
for (let KEY in obj)
{
//Pushing data to other array as object
this.finalData.push({ [KEY] : obj[KEY] });
}
}
const tStyles = [];
for (const i of iStyles) {
const temp = {};
temp[`${style}`] = `../dist/css/uikit.${wFile}.${style}.css`;
tStyles.push(temp);
}
json : {"black-beige":"../dist/css/uikit.or.black-beige.css"}

Randomly select enumerable property of object in Javascript

Given a dictionary-like object in Javascript such as {a:1, b:-2, c:42}, is there a simple way to randomly choose a property?
In the above example, I would like to have a function that would return a, b or c randomly.
The solution I've come up with is like the following:
var proplist = []
forEach(property in foo) {
if(propertyIsEnumerable(foo[property]) {
proplist.push(property);
}
}
var n = proplist.length;
// randomly choose property (randInt(n) returns a random integer in [0,n))
proplist[randInt(n)];
Is there a more idiomatic way to do this?
Use Object.keys (or even Object.getOwnPropertyNames) to get a list of all properties. Then, select a random property by multiplying Math.random() with the length of the list, floored.
var propList = {}; //...
var tmpList = Object.keys(propList);
var randomPropertyName = tmpList[ Math.floor(Math.random()*tmpList.length) ];
var propertyValue = propList[randomPropertyName];
This can be quite idiomatic with underscore.js:
randomProp = _.shuffle(_.keys(obj))[0]
Edit: actually, one should use _.sample for that.
Or if you want to write a reusable function for this, you could do
const randomFrom = list => list[Math.floor(list.length * Math.random())];
const randomProp = obj => randomFrom(Object.keys(obj));
randomProp(propList); //=> one of the keys of propList
This will return undefined if your object has no properties, but that's probably the best we could do in any case.

Get the first key name of a JavaScript object [duplicate]

This question already has answers here:
How to access the first property of a Javascript object?
(23 answers)
Closed 3 years ago.
Let's assume we have the following JavaScript object:
ahash = {"one": [1,2,3], "two": [4,5,6]}
Is there a function that returns the first key name for the given object?
From the example above I want to get one as a result of that function.
In Javascript you can do the following:
Object.keys(ahash)[0];
You can query the content of an object, per its array position.For instance:
let obj = {plainKey: 'plain value'};
let firstKey = Object.keys(obj)[0]; // "plainKey"
let firstValue = Object.values(obj)[0]; // "plain value"
/* or */
let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]
console.log(key); // "plainKey"
console.log(value); // "plain value"
There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:
for (var k in ahash) {
break
}
// k is a key in ahash.
Try this:
for (var firstKey in ahash) break;
alert(firstKey); // 'one'
If you decide to use Underscore.js you better do
_.values(ahash)[0]
to get value, or
_.keys(ahash)[0]
to get key.
With Underscore.js, you could do
_.find( {"one": [1,2,3], "two": [4,5,6]} )
It will return [1,2,3]
I use Lodash for defensive coding reasons.
In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.
A "fully defensive" approach with Lodash would use both keys as well as get:
const firstKey = _.get(_.keys(ahash), 0);
you can put your elements into an array and hash at the same time.
var value = [1,2,3];
ahash = {"one": value};
array.push(value);
array can be used to get values by their order and hash could be used to get values by their key. just be be carryfull when you remove and add elements.

Categories