简体   繁体   中英

Logical OR in combination with lodash get() gives weird results

OK, so I can't wrap my head around this...

I need to find a bankScheme and there is some code before this snippet that might find it so I have set it to ABC to illustrate that the value was found. If it still wasn't found I wanted to try to find it from some other data, object j in the snippet below but as object j might not contain PaymentMeans I used the lodash _.get() to fetch the value (in the real object the path is much "deeper").

const _ = require('lodash');

let j = { PaymentMeans: '12' };
let bankScheme = 'ABC';
// Let's try the OR operand with a lodash function:
bankScheme = bankScheme || _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

console.log(_.get(j, 'PaymentMeans'), bankScheme);
// It now logs '12 58Found' which is very weird as it should log 'ABC' in any case, and even if it didn't find 'ABC' it should log '58NotFound'...
// If however bankScheme = null then the _.get() works as expected

The weird thing here is, firstly, that the logical OR ( || ) is not doing what I would expect it to, and that is to leave the value as ABC as it is not " falsy " to begin with.

Secondly, if we accept that the OR is not working, the return should be 58NotFound but now it is 58Found ...

What am I missing?

Writing it as this works as expceted though:

bankScheme = bankScheme ? bankScheme : _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

Code: https://repl.it/join/hjqoaatb-anderswa

Don't forget about the operator priority.

This

bankScheme = bankScheme || _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

is equivalent to this:

bankScheme = (bankScheme || _.get(j, 'PaymentMeans') === '58') ? '58Found' : '58NotFound';

You need to group correctly.

bankScheme = bankScheme || (_.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound');

You can find a good read about operator priorities here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM