2

I have this code:

  if (typeof my.nested.dataset !== "undefined") {
    my.nested.dataset.push(data);
  } else {
    my.nested.dataset = [data];
  }

I need to push data to an array but only if the array exists otherwise I need to create one.

I'm repeating my.nested.dataset three times. What alternatives do I have to append/assign at once.

isar
  • 1,661
  • 1
  • 20
  • 39
  • Possible duplicate of [javascript: check if array exist, if not create it](https://stackoverflow.com/questions/1961528/javascript-check-if-array-exist-if-not-create-it) – Rajesh Feb 21 '18 at 06:00
  • The answer below is more concise although the more important question is do you call that code in more than one place. If so, you should really put the code into a function say function addToNestedDataset(data). Then it doesn't really matter that your code is a bit more verbose as it is easier for the next perhaps less experience developer to read and understand. – Andrew Feb 21 '18 at 06:00

2 Answers2

3

You can initialize your dataset via my.nested.dataset = my.nested.dataset || [].

And then in the code you don't need to check with if. Just call push on it

 my.nested.dataset.push(data);

In one line

(my.nested.dataset = my.nested.dataset || []).push(data)
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

If you want to use a one-liner, it's

(my.nested.dataset = my.nested.dataset || []).push(data);

but that still repeats my.nested. If it's a really long name, make a helper variable for it. You cannot avoid repeating .data.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375