Elegant Javascript code to check for undefined values

So, I have a callback function that provides a json object:

function(object){
    var data=object.packet.link.ip.tcp.data;
    console.log(data.toString());
}

      

The problem is that any of the packages / links / ip / tcp / data can be "undefined" - my node.js program crashes every time it hits an undefined variable.

I tried to put the "data" declaration inside try / catch, however I keep getting "undefined" errors. I guess I will need to put the object / object.packet / object.packet.link / object.packet.link.ip / etc ... in try / catch.

So, I found some elegant coffee shops:

if object?.packet?.link?.ip?.tcp?.data? then doStuff()

      

which compiles to:

var _ref, _ref1, _ref2, _ref3;

if ((typeof object !== "undefined" && object !== null ? (_ref = object.packet) != null ? (_ref1 = _ref.link) != null ? (_ref2 = _ref1.ip) != null ? (_ref3 = _ref2.tcp) != null ? _ref3.data : void 0 : void 0 : void 0 : void 0 : void 0) != null) {
       //doStuff:
       var data = object.packet.link.ip.tcp.data;
       console.log(data.toString());
}

      

Ugh!

It works fine now, but I'm just wondering if there is a more elegant (readable) way to do this in pure Javascript?

+3


source to share


3 answers


You can do

["packet", "link", "ip", "tcp", "data"]
  .reduce(function (m, i) { if (m) return m[i]; }, object);

      



You can move reduce

into a function and have get(object, "packet", "link", "ip", "tcp", "data")

. This might be pretty, although a simple solution &&

might make more sense.

+5


source


If this is enough to check if you are dealing with the correct values, you can go like

var data = object && object.packet && object.packet.link && object.packet.link.ip; // etc.

      

there is still no beauty, but most likely the best you can go. Of course, you always have the option to introduce a good ol sentence try..catch

.



try {
    var data = object.packet.link.ip.tcp.data;
} catch( ex ) { }

      

Anything "better" than "elegance" (whoever defines it) will require a custom written function that steps through the object's properties step by step, checking for existence.

+3


source


function A(object)
{
 var data = object?object.packet?object.packet.link?object.packet.link.ip?object.packet.link.ip.tcp?  object.packet.link.ip.tcp.data:null:null:null:null:null;
 console.log(data);
}

      

  • Note

    If the data is null, you cannot call toString on null, since null (along with undefined) are the only two primitives that don't have object wrappers and then no toString () functions.

+1


source







All Articles