繁体   English   中英

检查对象javascript中是否存在嵌套属性

[英]Checking existence of nested property in an object javascript

我已经回顾了这个问题的一些答案,但是,我想以不同的方式提出我的问题。

假设我们有一个字符串: “level1.level2.level3 ....” ,表示名为Obj的对象中的嵌套属性。

关键是我们可能不知道该字符串中存在多少嵌套属性。 例如,它可以是“level1.level2”或“level1.level2.level3.level4”。

现在,我想要一个给出Obj和属性字符串作为输入的函数,只需告诉我们,如果对象中存在这样的嵌套属性(假设为true或false作为输出)。


更新:感谢@Silvinus,我发现了一个小修改的解决方案:

        private checkNestedProperty(obj, props) {
        var splitted = props.split('.');
        var temp = obj;
        for (var index in splitted) {
            if (temp[splitted[index]] === 'undefined' || !temp[splitted[index]]) return false;
            temp = temp[splitted[index]];
        }
        return true;
    }

您可以使用此功能探索您的Obj:

var fn = function(obj, props) {
        var splited = props.split('.');
        var temp = obj;
        for(var index in splited) {
            if(typeof temp[splited[index]] === 'undefined') return false;
            temp = temp[splited[index]]
        }
           return true
        }

var result = fn({ }, "toto.tata");
console.log(result); // false

var result = fn({ toto: { tata: 17 } }, "toto.tata");
console.log(result); // true

var result = fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata");
console.log(result); // false

此函数允许探索Obj的嵌套属性,该属性取决于参数中传递的props

您可以通过迭代键并检查它是否在给定对象中来使用Array#every()thisArg

 var fn = function (o, props) { return props.split('.').every(k => k in o && (o = o[k])); } console.log(fn({}, "toto.tata")); // false console.log(fn({ toto: { tata: 17 } }, "toto.tata")); // true console.log(fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata")); // false 

这个答案提供了你的问题的基本答案。 但需要调整它来处理未定义的情况:

function isDefined(obj, path) {
  function index(obj, i) { 
    return obj && typeof obj === 'object' ? obj[i] : undefined; 
  }

  return path.split(".").reduce(index, obj) !== undefined;
}

根据@Silvinus给出的解决方案,如果你在嵌套对象中处理数组,这是一个解决方案(因为在数据库查询的结果中通常就是这种情况):

checkNested = function(obj, props) {
    var splited = props.split('.');
    var temp = obj;
    for(var index in splited) {
      var regExp = /\[([^)]+)\]/;
      var matches = regExp.exec(splited[index])
      if(matches) {
        splited[index] = splited[index].replace(matches[0], '');
      }
      if(matches) {
        if(matches && typeof temp[splited[index]][matches[1]] === 'undefined') return false;
            temp = temp[splited[index]][matches[1]];
      }
      else {
            if(!matches && typeof temp[splited[index]] === 'undefined') return false;
                temp = temp[splited[index]]
      }
    }
    return true
}

obj = {ok: {ao: [{},{ok: { aa: ''}}]}}

console.log(checkNested(obj, 'ok.ao[1].ok.aa')) // ==> true
console.log(checkNested(obj, 'ok.ao[0].ok.aa')) // ==> false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM