loading...

Protip: JSON ignores 'undefined'

jamesscaur profile image James Scaur ・1 min read

Say you have a massive object with many nested variables:

"donkey" {
    "fur_pos": [
        [1, 2, 3],
        [1, 4, 3],
        [2, 2, 3]
        ...]
}

And say some of them are inconsistent:

"donkey" {
    "fur_pos": [
        [1, 2],
        [1, 4, 3, 7, 8],
        [2, 2, 3, 4]
        ...]
}

Usually you'd be out of luck if you tried to get the 4th array item of each list in fur_pos.

However, you can do it like this:

donkey.fur_pos.map(i => i[3] ? i[3] : undefined)

You'll be left with a list of:

[undefined, 7, 4]

And the 'undefined' attribute will simply be removed when you eventually use that mapped array.

[7, 4]

If you'd like to keep the positions, simply swap

donkey.fur_pos.map(i => i[3] ? i[3] : undefined)

for

donkey.fur_pos.map(i => i[3] ? i[3] : null)

Posted on Feb 15 '19 by:

jamesscaur profile

James Scaur

@jamesscaur

I build customer support tools for cryptocurrency exchanges. Check out https://txbatch.com/ and https://github.com/txbatch/charlie

Discussion

markdown guide
 

Since the value either exists or is undefined,

donkey.fur_pos.map(i => i[3] ? i[3] : undefined)

can be simplified to:

donkey.fur_pos.map(i => i[3])

It's inaccurate though to say that the undefined will be removed - in what way are you using it for which this is the case?

What you can do however is eg:

donkey.fur_pos
    .map(i => i[3])
    .filter(Boolean)

which will remove all falsey statements including undefined and null, but also 0 and false, so you may want a more robust filter function, depending on your objective.

 

+1 .filter(Boolean) is very elegant solution 😎