检查对象javascript

时间:2016-05-04 06:08:25

标签: javascript object properties nested

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

假设我们有一个字符串:“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;
    }

4 个答案:

答案 0 :(得分:3)

您可以使用此功能探索您的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

答案 1 :(得分:3)

您可以使用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

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:0)

基于@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
相关问题