0

If "a_b" does not exist then the following code throws back undefined - which is what I want:

var abc= json.reduce((a,c) => a.concat({xyz:c.a_b}), [])

However, if I do the following code and look for "media" within "a_b" that does not exist then I get a failure "Cannot read property 'media' of undefined".

var abc= json.reduce((a,c) => a.concat({xyz:c.a_b.media}), [])

Why is this the case?

In both cases "a_b" does not exist yet it is ok with the code if I just call that but not if I try and look for a property within it.

Is there a way to get around this?

For example, I am trying to use "|| null" but that doesn't seem to work within a concat, as below.

var abc= json.reduce((a,c) => a.concat({xyz:c.a_b.media || null}), [])
Erik Philips
  • 48,663
  • 7
  • 112
  • 142
JDT
  • 525
  • 1
  • 4
  • 13

1 Answers1

0

Don't use concat method it will create a new array instance, use push instead:

var abc = json.reduce((a, c) => {
      a.push({ xyz: c.a_b && c.a_b.media });
      return a;
}, []);
YouneL
  • 7,149
  • 2
  • 20
  • 44
  • Thanks for the reply -the && was actually the solution - I did just needed to add "xyz:c.a_b&&c.a_b.media" in the concat - so I didn't need to change anything except adding the && while keeping the concat – JDT Nov 07 '17 at 18:54
  • @YouneL `concat` makes no difference here since the new array is returned. – Gabriel Bleu Nov 07 '17 at 19:55
  • @GabrielBleu of course, using concat or push result to the same thing, but concat will create a new array instance every time in each iteration and return it, however push will use the same array reference. check this [benchmark](https://jsperf.com/javascript-array-concat-vs-push) – YouneL Nov 07 '17 at 21:45
  • @younel yes, instead of answering the question, you are suggesting an optimization, you should edit to make it clear. – Gabriel Bleu Nov 07 '17 at 22:04