-2

When pressureSeaLevelRate returns null I need to set it to 0

_currentData['pressureRate'] = data['observation']['pressureSeaLevelRate'];
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • what other values do you have? – Nina Scholz Dec 29 '22 at 17:13
  • 3
    `_currentData.pressureRate = data?.observation?.pressureSeaLevelRate ?? 0` – Mulan Dec 29 '22 at 17:14
  • What's wrong with a simple `if`? `if (... === null) { ... = 0 }` – Andreas Dec 29 '22 at 17:19
  • @MichaelM. If any of the already available questions here on SO have the same problem/topic like this one then use one of those to close the question as duplicate of that other question so we don't create yet another copy of an already available information/answer, – Andreas Dec 29 '22 at 17:58

3 Answers3

2

It looks like you want to use the ?? Nullish coalescing operator. Here's an example

const a = null;

const b = a ?? 0;
console.log(b)

const c = 1 + (a ?? 0);
console.log(c);

With your code, you can do this:

_currentData['pressureRate'] = data['observation']['pressureSeaLevelRate'] ?? 0;

or, as Mulan pointed out in the comments, if data or data.pressureSeaLevelRate could also be null, use:

_currentData.pressureRate = data?.observation?.pressureSeaLevelRate ?? 0
Michael M.
  • 10,486
  • 9
  • 18
  • 34
1

If you have only numbers and null, you could convert null to a number with unary +.

let value = null;

value = +value;

console.log(value);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Try this


_currentData['pressureRate'] = Number(data['observation']['pressureSeaLevelRate']);

codester_09
  • 5,622
  • 2
  • 5
  • 27