Check if there is a value in Node JS

Asked

Viewed 47 times

0

Hello

I have a variable in Nodejs that sometimes comes with the following content:

{ '$instance': {} }

and sometimes it comes like this:

{
 '$instance': { numeropessoas: [ [Object] ] },
  numeropessoas: [ '2' ]
}

How can I know (make an IF) which check came with the "numeropessoas"? I need to know because I want to try to take the value of it this way: "step. _info.options.numero pessoas[0];" and when it does not exist, it is causing me an error.

  • You can check by doing if ('numeropessoas' in step._info.options)

2 answers

1

From the version 14.0 of Node.js you can use the optional chaining to directly obtain the value you need:

const data = {
  '$instance': { numeropessoas: [{ x: 'x' }] },
  numeropessoas: ['2']
};

console.log(data.options?.numeropessoas?.[0]);

If no property exists numeropessoas or it is null, the result will be only undefined:

const data = {
  '$instance': { numeropessoas: [{ x: 'x' }] }
};

console.log(data.numeropessoas?.[0]);


Optional chaining

The optional chaining operator ?. allows the reading of the value of a property located internally in a chain of connected objects, without the validation of each chain reference being expressively performed.

The operator ?. works in a similar way to the operator . chaining, except that instead of causing an error if the reference is nullish (null ou undefined), the expression undergoes a "short-circuit" and returns with a value of undefined.

0

Utilizes the hasOwnProperty which verifies that an object has a certain key:

let var = { '$instance': {} };

var.hasOwnProperty('numeropessoas'); // false


var = {
 '$instance': { numeropessoas: [ [Object] ] },
  numeropessoas: [ '2' ]
};

var.hasOwnProperty('numeropessoas'); // true

// O seu if fica assim
if (var.hasOwnProperty('numeropessoas')) {
  // Tem numeropessoas
} else {
  // Não tem numeropessoas
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.