Unable to get length value of array in Node Red JavaScript
P粉216807924
P粉216807924 2024-01-28 22:21:45
0
1
517

I want to know the length of an array read inside a function in NodeRed using JavaScript, but it doesn't display/return any value. Can anyone help me?

This is the code inside the function block in Node-Red

let j = 0;
let array1 = { payload: msg.payload };

j = array1.length;

return j;

I don't see any return value for j. Any help?

I expected the value of j to be displayed on the NodeRed debug console.

P粉216807924
P粉216807924

reply all(1)
P粉637866931

This is the actual answer to your question. Please pay attention to these matters given below;

  1. let array1 = { payload: msg.payload } is not an array. It is an object. The length of the object cannot be found via obj.length; instead use Object.keys(array1).length

If you want to find the length (number of properties) of an object, use the following code snippet.

let array1 = { payload: msg.payload };
let length = Object.keys(array1).length;
console.log(length);


// Example
let person = {name: "Mehdi", city: "Jamshoro", country: "PK"}
let length = Object.keys(person).length;
console.log(length);

// Output: 3

The length of the array can be found by:

let arr = [1,2,3,4,5,6]
console.log(arr.length)

// Output: 6

You appear to be using a return statement outside a function. return Has no effect outside a function. Use console.log() instead.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template