If(.. && ...) Please help with this bit of code

I have never been good at handling this structure.

This bit of code should (maybe even did used to) work.

But now it is failing and I am getting 22 for x.

if(Array.isArray(msg.table) && msg.table.length)
    x = msg.table[m];
} else
    x = 22;             //  Default if not set.

The payload going in looks like this:


Where have I messed up?
(or better:
What code do I need so it gives me the desired 32 instead of the default 22?)

msg.table is an object, not an array in the example you have given.

Ok, so the second test in the if will fail.

(Idiot hat on)

What do I need to get it to work?

(Though I see SteveMcl is replying)

msg.table is not an array. It's an object.

Try if(msg.table && Object.keys(msg.table).length)

1 Like

Thanks Steve.

If you have control of the data then change it so that it is an array.

I kind of do and don't.

I have a flow.table which is the same structure.... an object.
I lookup the value from the month as shown in the code from the code I posted above.

I was going to access the flow level, but put that into the message before the node and parsed it as part of the incoming message.

What would be the advantage of making it an array rather than an object?

Efficency, plus simpler to access. The fact that you intuitively thought it was an array is a giveaway.

x = (msg.table[m] || 22);
work the same?

I'm not sure that is the correct use of the term intuitively. :wink:

I'll go off and see if I can work out how to use arrays.

Using or based on what one feels to be true even without conscious reasoning.

So if you didn't use conscious reasoning to determine that it was an array, but just felt that it was, then that was intuitive.

Maybe. But stupidity is a good contender as well.

I have a lot of incorrect associations between things and use them wrongly often.

Anyway, I'll keep looking at arrays.

Lines like this don't help me:
Arrays are a special type of objects
(Just mentioning)

So the advantage I can discern is that rather than needing two entries per line (as mine has the month value and then the value I want) I would only need one entry. That being the value.

Am I correct?

Plus the vast set of Array functions that you get with arrays to allow handling them. So they are generally much easier to deal with (for data that lends itself to being in an array).

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.