Evaluate an object looping back its nodes

The situation is that you want to avoid lines like this one here

if (object.key == null || typeof(object.key)=== "undefined" || object.key==="")


Which can be terrible when there areĀ object.grandparent.parent.child and any of them could be undefined.

Considering that eval() isn’t evil, just misunderstood, this solution verifies that all the nodes exist and the “leaf” has a value other than “”

function hasContent(obj, string) {
    st = string.split(".");
    var key, v;
    try {
        for (v = 0; v < st.length; v++) {            
            if (eval("obj."+[key]) === null ||  typeof (eval("obj."+[key])) === "undefined") return false;
        if (eval("obj."+[key])=="") return false
    catch (e) { return false; }
    return true;


The usage is fairly simple: just call the function sending your object and the string having the full path

if (hasContent(timeEntry,"UserComments.UserComment"))


Eval, not evil

Published by

Nelson Muskus

Full Stack developer

Leave a Reply

Your email address will not be published.