将嵌套键设置为False

时间:2016-12-14 17:05:55

标签: javascript loops object

我有一个看起来像这样的对象:

var access = {
  main: false,
  createCatalog: {
    enterCatalogDetails: false,
    selectProducts: true,
    previewStyles: true,
    previewLayout: false
  },
  createBoard: {
    enterBoardDetails: false,
    selectProducts: false,
    previewLayout: false
  }
}

对于每个键,我想将值设置为false。

我有以下函数将资产对象传递给:

 function setInvalidObject (obj){
      var objCount = 0;
      for(var p in obj){
        if(obj.hasOwnProperty(p)){
          objCount++;
          setInvalidObject(obj[p]);
        }
      }
      if(objCount === 0){
        obj = false;
      }
    }

它尝试运行,并在需要将密钥设置为false的任何地方调用自身。问题是,它似乎在中途覆盖自己,我无法弄清楚为什么会发生这种情况。

1 个答案:

答案 0 :(得分:1)

您需要检查属性是否为对象,然后迭代对象。然后继续循环。如果不是对象,请将值设置为false。您不需要自己的属性计数器。

function setInvalidObject(obj) {
    var objCount = 0;
    for(var p in obj){
        if (obj.hasOwnProperty(p)) {
            if (obj[p] && typeof obj[p] === 'object') {
                setInvalidObject(obj[p]);
                continue;
            }
            obj[p] = false;
        }
    }
}

var access = { main: false, createCatalog: { enterCatalogDetails: false, selectProducts: true, previewStyles: true, previewLayout: false }, createBoard: { enterBoardDetails: false, selectProducts: false, previewLayout: false } };

setInvalidObject(access);
console.log(access);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或使用Object.keys并跳过支票hasOwnProperty

function setTo(object, value) {
    Object.keys(object).forEach(function (k) {
        if (object[k] && typeof object[k] === 'object') {
            setTo(object[k], value);
            return;
        }
        object[k] = value;
    });
}

var access = { main: false, createCatalog: { enterCatalogDetails: false, selectProducts: true, previewStyles: true, previewLayout: false }, createBoard: { enterBoardDetails: false, selectProducts: false, previewLayout: false } };

setTo(access, false);
console.log(access);
.as-console-wrapper { max-height: 100% !important; top: 0; }