使用未定义值为嵌套对象设置默认值的最简单方法

时间:2013-10-08 07:45:29

标签: javascript json undefined

我有一个JSON字符串。我使用它通过dataLayer将数据推送到Google跟踪代码管理器。示例:如果页面是联系人,那么我将hitDetails中的所有内容作为嵌套变量推送。

var dataLayerRepo = {
'/contact': {'hitDetails': {'act': {'type': 'views'}, 'dirObj': {'name': '/contact-us','type': '/page','id': window.location.search+window.location.hash}} }, 
'/': {'hitDetails': {'act': {'type': 'views'}, 'dirObj': {'name': '/homepage','type': '/page','id': window.location.search+window.location.hash,'class': {'lev0': '/booking-process'}}} }, 
};

我的问题是,对于某些页面,我在hitDetails中有字段,其他字段中不存在(如class和class.lev0)。我可以让JSON本身中的字段具有空值,但我希望保持代码膨胀并仅推送具有值的字段。

所以我使用这个函数来检查嵌套级别,但它看起来很麻烦和麻烦。

我不擅长JS,但有一种更简单的方式可以说“你试图在{{hitDetails}}(GTM中的变量)中访问的任何嵌套值,如果它不存在则只返回一个空字符串“。

var o = {{hitDetails}};

function checkNested(obj /*, level1, level2, ... levelN*/) {
  var args = Array.prototype.slice.call(arguments),
      obj = args.shift();
      for (var i = 0; i < args.length; i++) {
        if (!obj.hasOwnProperty(args[i])) {
          return false;
        }
        obj = obj[args[i]];
      }
      return true;
}

if (checkNested(o, 'act') == false) { 
    o.act = [];
};

if (checkNested(o, 'act','type') == false) { 
    o.dirObj.act.type = "";
};

谢谢!

1 个答案:

答案 0 :(得分:0)

似乎你想尝试通过变量获取值。 而且,变量来自具有级别的对象。

如果我是你,我会检查变量而不是“checkNested()”。

示例:

function isEmpty(v, defValue) {
    return (typeof (v) == 'undefined') ? defValue : v;
}

if( isEmpty(o.act.type, false) !== false ){
    console.log( 'o.act.type: ' + o.act.type );
}
console.log( 'o.act.keyNotExists: ' + isEmpty(o.act.keyNotExists, 'default value') );