How to check if object within object exists

后端 未结 6 824
慢半拍i
慢半拍i 2021-01-12 08:21

It seems that the following technique for checking the existence of an object member produces an error because the \'bar\' parent object hasn\'t been declared before the che

6条回答
  •  滥情空心
    2021-01-12 08:58

    You could wrap it up into a method:

    function checkGraph(obj, graphPath)
    {
      var parts = graphPath.split(".");
      var root = obj;
    
      for (var i = 0; i < parts.length; i++)
      {
        var part = parts[i];
        if (root[part] && root.hasOwnProperty(part))
          root = root[part];
        else
          return false;
      }
    
      return true;
    }
    

    Where you could call it as:

    var foo = {},
        newVal = checkGraph(foo, "bar.myVal") ? foo.bar.myVal : null;
    

提交回复
热议问题